In object oriented programming languages such as C++, a destructor is a common method of a class, automatically called when an object is destroyed. In many cases this works out fine – the method simply needs to make sure that all resources allocated by an object of this type are released. However, in other than simple non-polymorphic classes, there is an extra complication. To quote from the ten commandments for C++ programmers: “Thou shalt declare and define the destructor as virtual such that others may become heir to the fruits of your labors.”.

But why do this? How does it help?

Virtual

The answer can be found by thinking about why we use the keyword virtual at all. To recap, a virtual method is used when we want to derive from a class, and allow access to derived classes through the interfaces provided by the base class. For example, take the class foo, and its derivative bar. foo contains a method DoSomething, which bar overrides. If we create an instance of bar through a pointer to a type of foo:

foo *obj = new bar();

and then call the DoSomething method of obj:

obj->DoSomething();

what happens? Something undesirable – instead of the code defined in bar being executed, we find that the foo version of DoSomething is called instead. The fix is simple – declare DoSomething as a virtual function in the base class foo, and the compiler will be more intelligent about which version of the method it calls.

Destructors

So, imagine the above example, but with destructors. What if bar declares a massive dynamic array which is cleaned up in its own destructor?

delete obj;

With a non-virtual destructor in the base class, bar's destructor isn't called at all, and we suffer a horrid memory leak where a large clump of memory isn't freed when it should be. The magic keyword “virtual” fixes this, and allows us to do the things that object oriented programming was designed to do.

Can you think of any advantages of a NON-virtual destructor?