1

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.

2
  • where do you allocate the memory to Data_array? Commented May 17, 2015 at 11:41
  • 4
    CData shouldn't inherit from CPerson. A list of people is not a person. Commented May 17, 2015 at 11:42

2 Answers 2

3

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à.

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

Comments

-1

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

8 Comments

Deleting Data_array in the destructor is not the only thing required to make this class safe.
Please tell me, which one?
What do you mean "which one"?
The other things required
For example operator= should also be overloaded. Second of all what if CPerson constructor throws an exception? Then you have memory leak. And so on and on.
|

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.