Summary: In this tutorial, we will learn about virtual destructor in C++ with examples.

Introduction to Virtual Destructor

Virtual Destructor in C++ is used to free up the resources used by the derived class object during object deletion.

The main focus is to make the base class’s destructor a virtual method so that the derived class destructor could be invoked at the time of object deletion.

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 rewrite this code but with a base class’s virtual destructor.

C++ Example using Virtual Destructor


We successfully freed the allocated memory using the destructor.

These are some 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.

In this tutorial, we learned what is the virtual destructor, why, and how to use virtual destructor in C++.

Leave a Reply