We can make destructors virtual. Let us read the code in listing 6.
Listing 6: | virtualdestructor |
The output of this program is "B::~B(void)", followed by "A::~A(void)". This means class B gets to execute its destructor, which in return invokes the destructor of class A implicitly (but after B::~B(void) is done).
This is much better than the non-virtual case. This time, a dynamically allocated object of class B gets to call the destructor specific to B. This destructor may contain code to clean up data members that are specific to class B.