0

This is my code i am getting error in initializing the char array in the constructor. i have also tried to initialize it with a string but all in vain . good help will be appreciated.

#include <iostream>
using namespace std;
class employe
{
    char name[30];
    int id;
public:
    employe(int a, char b[30] ) :id(a), name(b)
    {

    }
    char getid()
    {
        return name;
    }

};
1

1 Answer 1

1

The problem is that when an array is passed to a function (and the constructor is just a function) then it will decay to a pointer to its first element.

That means the argument b in your constructor is really a pointer (type char*), and you can't initialize an array from a pointer.

The simplest solution is to copy from the pointer to the array inside the constructor body:

// Copy the string from b to name
// Don't copy out of bounds of name, and don't copy more than the string in b contains (plus terminator)
std::copy_n(b, std::min(strlen(b) + 1, sizeof name), name);

A better solution is to use std::string for strings, and then you can initialize like you attempt to do now.

Sign up to request clarification or add additional context in comments.

1 Comment

@KashifMehmood3314-FBASBSSEF1 It it worked and solved your problem, then please consider marking this as accepted by clicking the checkbox next to the answer. And please take some time to read the help pages, and take the Stack Overflow tour.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.