Virtual destructor in C++

Virtual destructors are useful when you can delete an instance of a derived class through a pointer to base class.

Here is an example when you don’t use virtual destructors.

class Base
{
  public:
     Base() {cout << "Base Constructor called";}
     // Base destructor is not virtual.
     ~Base() {cout << "Base Destructor called";}
};

class Derived :public Base
{
    public:
       Derived() {cout << "Derived Constructor called";}
       ~Derived() {cout << "Derived Destructor called";}
};

void main()
{
    Base *pBase = new Derived();

    delete pBase;    // Here is the problem.
};

Since Base’s destructor is not virtual and pBase is a Base pointing to a Derived object, delete pBase has undefined behavour. In most implementations, the call to the desturcotr will be resolved like any non-virtual cade, meaning that the destrutor of the base class will be called but not the one of the derived class, resulting in resource leak.
For example, here is the output of the above code:

Output:
Base Constructor called
Derived Constructor called
Base Destructor called

If we want the destructor of Derived to be called we must make the base destructor virtual.

class Base
{
  public:
     Base() {cout << "Base Constructor called";}
     // Base destructor is virtual.
     virtual ~Base() {cout << "Base Destructor called";}
};

The new input will be as follows. Note, that the deconstruction of objects is called in reverse.

Output:
Base Constructor called

Derived Constructor called
Derived Destrucotor called
Base Destructor called

To sum up, always make base classes destructors virtual when they are meant to be manipulated polymorphically.

If you want to prevent the deletion of an instance though a base class pointer, you can make the base class destructor protected and non-virtual. By doing so, the compiler won’t let you call delete on a base class pointer.

Posted in C++

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s