Solution

The main code allocates a Derived object on the heap but uses a Base pointer to store its address, exploiting polymorphism. Since the destructor is not declared virtual, the binding occurs at compile-time: since thePtr is of type Base*, the destructor called is the one for the Base class even though thePtr actually points to an object of type Derived.

As is said in the ``C++ Gotchas'' book by S. Dewhurst (gotcha #70), this bug causes unpredictable behaviour.

Chances are you'll just get a call of the base class destructor for the derived class object: a bug. But the compiler may decide to do anything else it feels like (dump core? send nasty email to your boss? sign you up for a lifetime subscription to ``This week in Object-Oriented COBOL''?).



Leo Liberti 2008-01-12