3

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?

2

3 Answers 3

2

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 );
}
Sign up to request clarification or add additional context in comments.

Comments

1
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){}

2 Comments

Can you please explain me what you did in the typedef line?
@XEvans He created a type alias: now ids_t is a type name that is the same type as std::array<int, 9>.
1

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.

Comments

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.