jamesalone
jamesalone

Reputation: 341

Fail to call destructor of other class C++

So I have this code, and when I run it, I got a run time error when class B is trying to call its destructor. The destructor of class A seems fine. I wonder what's wrong with this code. Thanks for helping.

#include <iostream>

using namespace std;

class A{
    public:
        //Constructor
        A(int N){
            this->N = N;
            array = new int[N];
        }

        //Copy Constructor
        A(const A& A1){
            this->N = A1.N;

            //Create new array with exact size
            this->array = new int[N];

            //Copy element
            for(int i=0; i<N; i++){
                this->array[i]= A1.array[i];
            }
        }

        ~A(){
            delete [] array;
            cout<<"Success"<<endl;
        }

        int N;
        int* array;
};

class B{
    public:
        B(const A& array1){
            array = new A(array1);
        }

        ~B(){
            delete [] array;
        }

        A* array;
};

using namespace std;

int main(){
    A matrix1(10);
    B testing(matrix1);

    return 0;
}

Upvotes: 0

Views: 70

Answers (3)

Omar Natour
Omar Natour

Reputation: 111

Remove the [] when you delete the allocated memory in b because you allocated for just one element and the [] makes the compiler assumes that you are deleting an array allocated memory.

Upvotes: 0

GEMQ
GEMQ

Reputation: 11

you can't use the delete [] when you don't create an array of elements, your destructor must be like:

~B(){
        delete  array;
    }

Upvotes: 1

danielschemmel
danielschemmel

Reputation: 11116

In B::~B(), you call delete[] on B::array after allocating it via new in B::B(const A&).

This is illegal: You must always pair new with delete and new[] with delete[].

Upvotes: 7

Related Questions