Sobes.tech
Middle

Why is a virtual destructor needed in C++?

sobes.tech AI

Answer from AI

When deleting a base class object through a pointer to the base class that actually points to a derived class object, a virtual destructor guarantees that the derived class destructor is called before the base class destructor. This is necessary for the proper release of resources allocated by the derived class. If the base class destructor is not virtual, only the base class destructor will be called, leading to resource leaks.

#include <iostream>

class Base {
public:
    Base() { std::cout << "Base Constructor\n"; }
    
    // Virtual destructor
    virtual ~Base() { std::cout << "Base Destructor\n"; }
};

class Derived : public Base {
public:
    Derived() { std::cout << "Derived Constructor\n"; }
    
    // Must be called after Derived's destructor
    ~Derived() override { std::cout << "Derived Destructor\n"; } 
};

int main() {
    Base* obj = new Derived(); // Base class pointer to a derived object
    
    delete obj; // Calling a virtual destructor leads to ~Derived() and ~Base() being called
    
    return 0;
}

Without a virtual destructor, the output would be:

Base Constructor
Derived Constructor
Base Destructor 

With a virtual destructor, the output is:

Base Constructor
Derived Constructor
Derived Destructor
Base Destructor