April 11th, 2006, 7:08 am
> A* a = new B;> delete a; >> In this case the dtor for A will be called and B's dtor won't be called and we have a memory leak. So, the point of making dtor in A > virtual is to call the dtor in B and then dtor in A? Is that correct? That's correct, only A's destructor is called. This need not necessarily be a memory leak though (for example if B's destructor does not release any memory at all). In general, the rule is: Base classes with no virtual destructor are not suited for inheritance.> What happens if we have code like:> B* b = new B;> delete b;First B's destructor is called, then A's, so no problem here, no memory leaks.>Can someone explain to me how an object of derived class is destructed? Is the objects dtor called first and then the base class's >dtor?Correct, the order of destruction is the reverse of the order of object construction. When creating an object of type B, first A's constructor is first called, then B's. When deleting an object, first B's destructor is first called and then A's. If during object creation, A's constructor were throwing an exception, no destructor would be called; if B's constructor were throwing an exception, the exception mechanism would only call A's destructor.