Virtual Destructor in C++ plays an important role in deleting the derived class object using a base class pointer.

To understand the significance of virtual destructor, consider the following example.

C++ Example without using Virtual Destructor


In the above example, we used inheritance and created a derived class object using the base class pointer.

After that we delete the object to free its allocated memory.

Notice the output, Only the base class destructor is called when we deleted the derived class object.

Because the derived class destructor has not been called, the raw integer pointer n has not been deleted from the memory hence causing memory leak. This causes undefined behavior.

To correct this we should define the base class destructor as virtual. So that the derived class destructor also gets invoked and we can explicitly delete the raw pointer.

Let’s implement the virtual destructor and improve our C++ code.

C++ Example using Virtual Destructor


We successfully freed the allocated memory using the destructor.

There are some final points one should note about polymorphism and destructors in C++.

  • Derived objects must be destroyed in the correct order starting at the correct destructor.
  • Always provide a public virtual destructor.
  • If base class destructor is virtual then all derived class destructors are virtual.

Any suggestions or doubts then comment below.

Leave a Reply