Sobes.tech
Middle

In which cases is it necessary to declare a destructor as virtual?

sobes.tech AI

Answer from AI

When a base class is used to create a polymorphic hierarchy (i.e., with derived classes accessible through base class pointers or references), and objects of derived classes are deleted through a base class pointer, it is essential to declare the destructor of the base class as virtual.

If the base class destructor is not virtual, deleting a derived class object through a base class pointer results in undefined behavior, typically only the base class destructor being called, and the derived class destructor not being invoked. This can lead to resource leaks or other cleanup issues.

Example:

class Base {
public:
    virtual ~Base() { /* cleanup code */ }
};

class Derived : public Base {
public:
    ~Derived() override { /* cleanup code */ }
};

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

If the destructor in Base is not virtual, the behavior of delete on a derived object through a base pointer is undefined, which often results in only the base destructor being called, and the derived part not being cleaned up properly.

In which cases is it necessary to declare a… - sobes.tech