Polymorphism and Destructors

A problem

If an object with a non-virtual destructor is explicitly destroyed by applying the delete operator to a base class pointer, only the base class destructor is invoked. Shape *sp = new Circle; delete sp; // calls Shape's destructor // if the destructor is not virtual The Circle object is not "fully" destroyed.

The solution

Declare a virtual destructor for any base class with at least one virtual function. virtual ~Shape ( ); Now, Shape *sp = new Circle; delete sp; will invoke the Circle destructor, which in turn invokes the Shape destructor.


Last Modified: Monday, 28-Aug-2006 10:16:04 EDT