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 for the object of class A will only be called if delete is called for that object. Make sure to delete that pointer in the destructor of class B.
For a little more information on what happens when delete is called on an object, see: http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.9
When you call delete on a pointer allocated by new, the destructor of the object pointed to will be called.
If you have a usual pointer (
A*
) then the destructor will not be called (and memory forA
instance will not be freed either) unless you dodelete
explicitly inB
's destructor. If you want automatic destruction look at smart pointers likeauto_ptr
.You have something like
If you then call
delete b;
, nothing happens to a, and you have a memory leak. Trying to remember todelete b->a;
is not a good solution, but there are a couple of others.This is a destructor for B that will delete a. (If a is 0, that delete does nothing. If a is not 0 but doesn't point to memory from new, you get heap corruption.)
This way you don't have a as a pointer, but rather an auto_ptr<> (shared_ptr<> will do as well, or other smart pointers), and it is automatically deleted when b is.
Either of these ways works well, and I've used both.
no it will not call destructor for class A, you should call it explicitly (like PoweRoy told), delete line 'delete ptr;' in example to compare ...