Virtual Destructors

Interview questions often ask about virtual destructors and why they are needed. It’s one of those funny things about C++ that unless you have specifically been shown, you just might not realise you need to know.

So why do you need a virtual destructor?

Essentially, you need a virtual destructor to make sure that ALL the relevant destructors are called when you delete an object via a base class pointer.

Huh?

Well, that actually sounds far more complicated than it is.

Let’s use an example to make it easier. Imagine you have a base class called Container and a sub class called CardboardBox. You create a CardboardBox, and then use the base class pointer to access it (why? see below). When you’re all done, it’s time to delete your object.

Now, the base class doesn’t do much in the way of clearing up, but the subclass (the cardboard box), can be recycled.

So, when your base class destructor is virtual, deleting the base class pointer will call the sub class destructor without you having to do anything extra – and the box will be recycled as if by magic.

If, however, your base class destructor is not virtual, only the base class destructor will get called and the recycling will not happen. Very bad for the environment.

Ouch.

Let’s see this in action with a code example:

#include <iostream> 
using namespace std;

class Container
{
public:
	Container() {};
	virtual ~Container()
	{
		cout << "Base class destructor called - not much to do." << endl;
	};
};

class CardboardBox: public Container {
public:
	CardboardBox() {};
	~CardboardBox()
	{
		cout << "Sub class destructor called - let's recycle the cardboard!" << endl;
	};
};

int main()
{
	CardboardBox* box = new CardboardBox;

	Container* p = box;

	delete p;

	return 0;
}

When the destructor is virtual (as it should be), the output of this program is as follows:

virtual1

You can see that both the sub class and the base class destructors have been called, and you have been a green and conscientious consumer.

However, if you remove the ‘virtual’ keyword from the base class destructor, the output changes to this:

virtual2

Oh dear. No one recycled their cardboard today.

So you see, making your base class destructors virtual will help keep everything nice and tidy. Which is of course, just how we like it 🙂

Why are you using a base class pointer to access the cardboard box?

This is the key to polymorphism in C++. You can use a base class to interface with objects without knowing what they are. So in this example you can talk to objects via the base class (Container), and you don’t need to specifically know whether they are cardboard boxes, metal boxes, or wicker baskets!

I’ve a fuller explanation of polymorphism here.