Why do we need a pure virtual destructor in C++?



Need a pure virtual destructor in C++

In C++, the main factor where a pure virtual destructor is needed are with abstract classes and polymorphism. It make sure proper clean-up and avoids memory leaks when working with objects of derived classes through base class pointers.

If a class has a virtual function, it's usually meant to be used polymorphically, which means that objects of derived classes can be used the same way as objects of the base class.

When destroying instances of a derived class using a base class pointer object, a virtual destructor is used to free up memory space allocated by the derived class object or instance.

Following are the key reasons why it needed:

  • Ensuring proper clean-up in base class.
  • Forcing abstract base class behaviour.
  • Promoting polymorphic destruction.
  • Supporting interface design.
  • Avoiding Object Slicing Issues.

Example of a pure virtual destructor

The following is a C++ example of a pure virtual destructor and how it ensures proper clean-up in an inheritance hierarchy:

#include <iostream>
class Base {
   public:
      // Pure virtual destructor
      virtual~Base() = 0;
   Base() {
      std::cout << "Base Constructor\n";
   }
};

Base::~Base() {
   std::cout << "Base Destructor\n";
}

class Derived: public Base {
   public: Derived() {
         std::cout << "Derived Constructor\n";
      }
      ~Derived() {
         std::cout << "Derived Destructor\n";
      }
};

int main() {
   Base * obj = new Derived();
   delete obj;
}

Following is the output of the above code:

Base Constructor
Derived Constructor
Derived Destructor
Base Destructor

Using a pure virtual destructor in inheritance hierarchy

Here is another example of using a pure virtual destructor in a C++ inheritance hierarchy, ensuring proper clean-up in a polymorphic setup:

#include <iostream>
class Animal {
   public:
      // Pure virtual destructor
      virtual~Animal() = 0;
   Animal() {
      std::cout << "Animal Constructor\n";
   }
};

Animal::~Animal() {
   std::cout << "Animal Destructor\n";
}

class Dog: public Animal {
   public:
      ~Dog() {
         std::cout << "Dog Destructor\n";
      }
};

int main() {
   Animal * pet = new Dog();
   delete pet;
   return 0;
}

The above code produce the following output:

Animal Constructor
Dog Destructor
Animal Destructor
Updated on: 2025-05-16T17:09:11+05:30

887 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements