What is the purpose of a virtual destructor in C++?

Understanding Virtual Destructors in C++

The primary purpose of a virtual destructor in C++ is to guarantee that when a derived class object is deleted through a base class pointer, the destructor of the derived class is correctly invoked. This is crucial for preventing memory leaks and other resource management issues in polymorphic hierarchies.

Without a virtual destructor, if you delete a derived class object using a base class pointer, only the base class destructor will be called. This can lead to the resources allocated by the derived class not being properly released, resulting in memory leaks and undefined behavior.

By declaring the base class destructor as virtual, you ensure that the correct destructor (the most derived one) is called when an object is deleted through a base class pointer. This mechanism allows for proper cleanup of resources across the entire inheritance hierarchy.

Example: Virtual Destructor


class Base {
public:
    virtual ~Base() {
        // Base class destructor
        // std::cout << "Base destructor called" << std::endl;
    }
};

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

int main() {
    Base* obj = new Derived();
    delete obj; // Calls Derived::~Derived() then Base::~Base()
    return 0;
}

In this example, delete obj; will correctly call Derived::~Derived() followed by Base::~Base(), ensuring all resources are deallocated.

bannerAds