0

I have a container class which contains a array of pointers to objects. Each of those objects hold another array of pointers to int. However when trying to delete the array of pointers to int, the program crashes giving the "Debug assertion failed!" error.

Here is the code I have:

#include <iostream>  
using namespace std;

class number_group
{
private:
    int *integers;
public:
    number_group()
    {
        integers = new int [10];
    }
    ~number_group()
    { 
        delete [] integers; 
    }
};

class group
{
private:
    number_group *num;
    int n;
public:
    group()
    {
        n = 0;
        num = new number_group [10];
    }
    ~group()
    {
        delete [] num;
    }
    void add(number_group N)
    {
        if (n + 1 < 10)
        {
            num[n++] = N;
        }
        else
        {
            cout << "limit reached";
        }
    }
};

int main ()
{
    group First;
    number_group A;
    First.add(A);

    getchar();
    return 0;
}
Edd
  • 1,982
  • 2
  • 21
  • 29

2 Answers2

0

You pass number_group by value, but it does not satisfy the Rule of Three. Neither does group.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

You need to define the copy constructor and the copy assignment operator for classes group and number_group.

The reason of the error is in these two statements

number_group A;
First.add(A);

After their execution two objects of type number_group points to the same array: the object with name A and the temporary object copied from A to the parameter of function add. After the temporary object will be deleted at the end of the statement First.add(A); the pointer in object A will be invalid.

Here is an example of the copy constructor and the copy assignment operator

number_group( const number_group &rhs )
{
    integers = new int [10];
    for ( int i = 0; i < 10; i++ ) integers[i] = rhs.integers[i];
}

number_group & operator =( const number_group &rhs )
{
    if ( this != &rhs )
    {
        int *tmp = new int [10];
        for ( int i = 0; i < 10; i++ ) tmp[i] = rhs.integers[i];
        delete []integers;
        integers = tmp;
    }

    return * this;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Okay I seem to understand the reason why I get the error, however how do I go about writing the copy constructors and the copy assignment operators for these classes? Sorry... This is the first time I'm dealing with dynamic arrays. – Edd Feb 27 '14 at 21:21
  • @double-trouble I had a typo in the assignment operator. I forgot the return statement. – Vlad from Moscow Feb 27 '14 at 21:39