When to use virtual destructors

Share

Overview

A virtual destructor is used to free the space which is assigned to the object of the derived class while we are trying to delete the instances of the base class using a pointer object of the base class. The destructor of the parent class uses the virtual keyword to ensure that at run time, both the base class and the derived class destructors are called. However, it will call the destructor of the derived class first and then the destructor of base class to release space that is occupied by both destructors.

Example

Let’s consider an example to understand this concept.

#include<iostream>
using namespace std;
class Vehicle
{
public:
Vehicle() //Constructor
{
cout<< "\n Constructor Vehicle class";
}
virtual ~Vehicle() // Destructor
{
cout<< "\n Destructor Vehicle class";
}
};
class Car: public Vehicle
{
public:
Car() //Constructor
{
cout << "\n Constructor Car class" ;
}
~Car() // Destructor
{
cout << "\n Destructor Car class" ;
}
};
int main()
{
Vehicle *ptr = new Car;
delete ptr;
}

Explanation

  • Line 3–14: We make a class named Vehicle and create a constructor and the virtual destructor in it.

  • Line 15–26: We make a class Car and inherit it with the Vehicle class and create a constructor and destructor in it.

  • Line 29–30: We call a pointer object which belongs to the Vehicle class. Then we call the constructor of the Vehicle class and then the Car constructor. And then we delete the pointer object which is occupied by the destructors of Vehicle and Car classes. So, the parent class pointer only removes the Vehicle class destructor without calling the destructor of the Car class. In order to prevent the memory leakage, we converted the destructor of Vehicle class into a virtual destructor so that it can call the destructor of the child class first and then the destructor of the parent class.