user13659234
user13659234

Reputation:

C++, should I call destructor?

In c++ I have a class which allocated memory using new[] so I wrote the destructor as following:

Matrix::~Matrix() {
    delete[] data;
}

My Matrix class contains field called complex which is a member of a class Complex that I wrote.

my question is, should I call the destructor for complex too, and how?

Upvotes: 0

Views: 633

Answers (2)

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29975

my question is, should I call the destructor for complex too, and how?

No, you do not have to call the destructors. That's the whole point of new/delete; they call the constructors/destructors.


Having said that, and considering it seems like you're new to C++, it's strongly advised to use std::vector<Complex> or std::unique_ptr<Complex[]> instead of raw pointers. Some of the reasons are:

  • Less likely to leak/double free; ownership is obvious.
  • Will not do erroneous "shallow" copy of pointers if you forget to add a copy constructor.
  • You don't have to worry about delete/delete[] mismatch.
  • vector can be resized/copied more easily.
  • In general provide an easier to use, harder to abuse, more encapsulated interface.

Upvotes: 0

asmmo
asmmo

Reputation: 7100

No the destructor of the outer class calls the destructors of inner data members.

If you compile and run the following code, u will see that the destructor of A, the class of the inner data member, is called although it hasn't been called explicitly in B destructor

#include <iostream>
struct A{
    ~A(){
        std::cout << "A des\n";
    }
};
struct B{
    A a;
    ~B(){
        std::cout << "B des\n";
    }
};
int main(){
    B b;
}

The out

B des
A des

Upvotes: 2

Related Questions