Ryncops
Ryncops

Reputation: 189

Creating and adding object from base class to derived class array

I have an issue with creating and adding objects into an array This is my base class:

class CPerson
{
    std::string first_name;
    std::string last_name;
    int birth_year;
    char sex;


public:
    CPerson();
    CPerson(std::string, std::string,int,char);

with some extra setters and getters. Then I have this derived class:

class CData :
    public CPerson
{
    int nrOfPersons;
    CPerson *Data_array; 
public:
    CData(int);
    ~CData();
};

In the constructor I want to fill the Data_array with person objects , and I do the following:

CData::CData(int x) : nrOfPersons(x)
{
    for (int i = 0; i < nrOfPersons; i++)
        Data_array[i] = CPerson();
}

But it crashes halfway there. I made the default CPerson() constructor to cout a message "Inserted" everytime I use it. So if I call in main CData database(4) it should print "Inserted" 4 times on the screen. Instead it only prints 2 times and then it crashes.

Upvotes: 1

Views: 271

Answers (2)

S&#233;bastien Garmier
S&#233;bastien Garmier

Reputation: 1263

You need to allocate memory for Data_array:

CData::CData(int x) : nrOfPersons(x)
{
    // allocate memory
    Data_array = new CPerson[nrOfPersons];

    // fill array
    for (int i = 0; i < nrOfPersons; i++)
        Data_array[i] = CPerson();
}

Don't forget to delete the allocated array afterwards (in a destructor for instance):

delete[] Data_array

Upvotes: -1

Shoe
Shoe

Reputation: 76240

You are trying to use a pointer to CPerson as an array. That would be true if you had dynamically allocated an array at construction, but that's a lot of hassle you don't really want to deal with.

Thankfully the C++ standard created a very useful utility called std::vector, that you can use:

class CData : public CPerson
{
    std::vector<CPerson> Data_array;
    // ...
};

and then:

CData::CData(int n) 
    : Data_array(n)
    {}

And the most beautiful thing about this is that your nrOfPersons member object also magically disappears. To retrieve the size you can just call Data_array.size() and voilà.

Upvotes: 3

Related Questions