Reputation:
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
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:
delete
/delete[]
mismatch.vector
can be resized/copied more easily.Upvotes: 0
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