Virtual destructor

A virtual destructor is used when you have a base class with a virtual function and you want to ensure that the destructor of the derived class is called properly when deleting an object through a pointer to the base class. The virtual destructor allows for proper destruction of resources allocated in the derived class.

Here’s an example to illustrate the concept:

#include <iostream>

class Base {
public:
    Base() {
        std::cout << "Base constructor called." << std::endl;
    }

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

class Derived : public Base {
public:
    Derived() {
        std::cout << "Derived constructor called." << std::endl;
    }

    ~Derived() {
        std::cout << "Derived destructor called." << std::endl;
    }
};

int main() {
    Base* basePtr = new Derived();  // Create a Derived object through a Base pointer

    delete basePtr;  // Delete the object using the Base pointer

    return 0;
}

In this example, we have a base class Base and a derived class Derived that inherits from Base. Both classes have their respective constructors and destructors defined. The Base class destructor is declared as virtual.

Inside the main() function, we create a Derived object using a Base pointer. When we call delete on the basePtr, the virtual destructor of Base is called first, and then the destructor of Derived is called. This ensures that the destructors of both classes are invoked in the correct order, even when deleting an object through a base class pointer.

The output of the program would be:

Base constructor called.
Derived constructor called.
Derived destructor called.
Base destructor called.

As you can see, the destructors are called in the reverse order of their constructors. Without the virtual destructor in the base class, only the base class destructor would be called, and the derived class destructor would be skipped, leading to potential resource leaks or undefined behavior.

Leave a Reply

Your email address will not be published. Required fields are marked *