XEvans
XEvans

Reputation: 31

C++ Initializing a array in a constructor

The .cpp :

 Person::Person(int _id[9], string name, int age) :_age(age), _name(name){};

The .h :

private:
int _id[9];
string _name;
int _age;

How do I intilaze the 'id' filed in the same method I did with age and name?

Upvotes: 3

Views: 145

Answers (3)

flogram_dev
flogram_dev

Reputation: 42888

Since you can't assign C-style arrays, or even initialize one with another, you could make the task simpler by using a C++-style array (which can be assigned and copy-initialized):

array<int, 9> _id;

and

Person::Person(array<int, 9> id, string name, int age)
: _id(id), _age(age), _name(name) { }

Or, if you insist on using a C-style array, you can copy the argument array to the member array with std::copy:

Person::Person(int id[9], string name, int age) : _age(age), _name(name)
{
   copy(id, id + 9, _id);
};

But note that passing a C-style array is bad because the compiler treats all C-style array arguments as being just pointers to the first element of the array. Thus the type of the id parameter is actually int* and hence the caller of the Person constructor can pass (using the implicit array-to-pointer decay) an array of any size, a pointer to just a single int, or even a nullptr, as demonstrated here. Trying to copy 9 elements from any of these invalid parameters will result in undefined behavior.

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

Arrays do not have a copy constructor and moreover the parameter _id in this constructor

 Person::Person(int _id[9], string name, int age) :_age(age), _name(name){};

is implicitly converted to pointer to the first element of the array passed in as an argument. That is actually the constructor looks like

 Person::Person(int *_id, string name, int age) :_age(age), _name(name){};

and the pointer does not keep the information whether it points to a single object or to the first object of an array.

So you should append this parameter with one more parameter that will specify the size of the underlaying array if such is paased as the argument.

For example

Person::Person(int *_id, size_t id_num, string name, int age) 
    :_id {}, _age(age), _name(name)
{
    size_t size = id_num < 9 ? id_num : 9;
    std::copy( _id, _id + size, this->_id );
}

Upvotes: 2

John Zwinck
John Zwinck

Reputation: 249592

class Person
{
    typedef std::array<int, 9> ids_t;
    Person(ids_t, string name, int age);

private:
    ids_t _id;
    string _name;
    int _age;
};

Person::Person(ids_t id, string name, int age) : _id(id),  _age(age), _name(name){}

Upvotes: 1

Related Questions