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;
    }

};
  • On an unrelated note, [don't do `using namespace std;`](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice), especially not [in a header file](https://stackoverflow.com/questions/14575799/using-namespace-std-in-a-header-file). – Some programmer dude Dec 21 '17 at 11:27

1 Answers1

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • @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](http://stackoverflow.com/help), and [take the Stack Overflow tour](http://stackoverflow.com/tour). – Some programmer dude Dec 21 '17 at 11:35