I have an class (A) which uses a heap memory allocation for one of it's fields. Class A is instantiated and stored as a pointer field in another class (B).
When I'm done with object B, I call delete, which I assume calls the destructor... But does this call the destructor in class A as well?
Edit:
From the answers, I take that (please edit if incorrect):
delete
instance of B calls B::~B();- which calls
A::~A();
and A::~A
should explicitlydelete
all heap-allocated member variables of A;- and finally the memory block storing said instance of B is returned to the heap - when new was used, it first allocated a block of memory on heap, then invoked constructors to initialize it, now after all destructors have been invoked to finalize the object the block where the object resided is returned to the heap.
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.
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
andshared_ptr
etc... are great for making this lifetime management much easier:You should delete A yourself in the destructor of B.
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
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).
When you do:
The destructor will be called only if your base class has the virtual keyword.
Then if you did not have a virtual destructor only ~B() would be called. But since you have a virtual destructor, first ~D() will be called, then ~B().
No members of B or D allocated on the heap will be deallocated unless you explicitly delete them. And deleting them will call their destructor as well.
I was wondering why my class' destructor was not called. The reason was that I had forgot to include definition of that class (#include "class.h"). I only had a declaration like "class A;" and the compiler was happy with it and let me call "delete".
No. the pointer will be deleted. You should call the delete on A explicit in the destructor of B.