Does delete on a pointer to a subclass call the base class destructor?
It is named "destructor", not "deconstructor".
Inside the destructor of each class, you have to delete all other member variables that have been allocated with new.
edit: To clarify:
Say you have
struct A {}
class B {
A *a;
public:
B () : a (new A) {}
~B() { delete a; }
};
class C {
A *a;
public:
C () : a (new A) {}
};
int main () {
delete new B;
delete new C;
}
Allocating an instance of B and then deleting is clean, because what B allocates internally will also be deleted in the destructor.
But instances of class C will leak memory, because it allocates an instance of A which it does not release (in this case C does not even have a destructor).
If you have a usual pointer (A*
) then the destructor will not be called (and memory for A
instance will not be freed either) unless you do delete
explicitly in B
's destructor. If you want automatic destruction look at smart pointers like auto_ptr
.
The destructor of A will run when its lifetime is over. If you want its memory to be freed and the destructor run, you have to delete it if it was allocated on the heap. If it was allocated on the stack this happens automatically (i.e. when it goes out of scope; see RAII). If it is a member of a class (not a pointer, but a full member), then this will happen when the containing object is destroyed.
class A
{
char *someHeapMemory;
public:
A() : someHeapMemory(new char[1000]) {}
~A() { delete[] someHeapMemory; }
};
class B
{
A* APtr;
public:
B() : APtr(new A()) {}
~B() { delete APtr; }
};
class C
{
A Amember;
public:
C() : Amember() {}
~C() {} // A is freed / destructed automatically.
};
int main()
{
B* BPtr = new B();
delete BPtr; // Calls ~B() which calls ~A()
C *CPtr = new C();
delete CPtr;
B b;
C c;
} // b and c are freed/destructed automatically
In the above example, every delete and delete[] is needed. And no delete is needed (or indeed able to be used) where I did not use it.
auto_ptr
, unique_ptr
and shared_ptr
etc... are great for making this lifetime management much easier:
class A
{
shared_array<char> someHeapMemory;
public:
A() : someHeapMemory(new char[1000]) {}
~A() { } // someHeapMemory is delete[]d automatically
};
class B
{
shared_ptr<A> APtr;
public:
B() : APtr(new A()) {}
~B() { } // APtr is deleted automatically
};
int main()
{
shared_ptr<B> BPtr = new B();
} // BPtr is deleted automatically
When you call delete on a pointer allocated by new, the destructor of the object pointed to will be called.
A * p = new A;
delete p; // A:~A() called for you on obkect pointed to by p