Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Virtual Destructor in C++



A virtual destructor is a destructor declared within the base class with a virtual keyword. In C++, destructors are special members of a class that frees memory occupied by an object when a memory leak occurs.

Deleting a derived class object using a pointer to a base class, the base class should be defined with a virtual destructor.

When to Use Virtual Destructor?

Virtual destructorsare needed in scenarios where polymorphism and inheritance are involved, and instances of derived classes are managed by pointers to base classes.

If our class has one or more virtual functions that are inherited from child classes and we are using a pointer to the base class to manage the objects, we need to implement the virtual destructor so that the proper version of the destructor is called when the object is deleted.

Implementation of Virtual Destructor

Let's see the basic C++ program to implement the virtual destructor:

#include<iostream>
using namespace std;
class Base {
   public: virtual~Base() {
      // Destructor implementation
      cout << "Base destructor called" << endl;
   }
};

class Derived: public Base {
   public:
      ~Derived() {
         // Destructor implementation
         cout << "Derived destructor called" << endl;
      }
};

int main() {
   Derived * d = new Derived();
   Base * b = d;
   delete b;
   return 0;
}

Following is the output of the code:

Derived destructor called
Base destructor called

Virtual Destructors in Inheritance

Let's see another C++ program to implement the virtual destructor:

#include <iostream>
using namespace std;

class base {
   public: base(int a, int b) {
      cout << "Constructing base\n";
      cout << "sum = " << a + b << endl;
   }
   virtual~base() {
      cout << "Destructing base\n";
   }
};

class derived: public base {
   public: derived(int a, int b): base(a, b) {
         // Explicitly calling base class constructor
         cout << "Constructing derived\n";
      }
      ~derived() {
         cout << "Destructing derived\n";
      }
};

int main() {
   derived * d = new derived(10, 20);
   base * b = d;
   delete b;
   return 0;
}

Following is the output of the code:

Constructing base
sum = 30
Constructing derived
Destructing derived
Destructing base
Updated on: 2025-05-27T16:32:51+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements