When to use virtual destructors
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
Vehicleand create a constructor and the virtual destructor in it. -
Line 15–26: We make a class
Carand inherit it with theVehicleclass and create a constructor and destructor in it. -
Line 29–30: We call a pointer object which belongs to the
Vehicleclass. Then we call the constructor of theVehicleclass and then theCarconstructor. And then we delete the pointer object which is occupied by the destructors ofVehicleandCarclasses. So, the parent class pointer only removes theVehicleclass destructor without calling the destructor of theCarclass. In order to prevent the memory leakage, we converted the destructor ofVehicleclass into a virtual destructor so that it can call the destructor of the child class first and then the destructor of the parent class.