Sobes.tech
Junior — Middle

When is it necessary to declare a destructor as virtual in a class?

sobes.tech AI

Answer from AI

It is necessary to declare the destructor as virtual in the base class if objects are expected to be deleted through a pointer to the base class, when the actual object is of a derived class. This is required for the correct invocation of derived class destructors and to prevent resource leaks.

Example:

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

class Derived : public Base {
public:
    ~Derived() { /* cleanup derived resources */ }
};

Base* obj = new Derived();
delete obj; // calls ~Derived(), then ~Base()

If the destructor of the base class is not virtual, deleting through a pointer to the base class will only invoke the base class destructor, and the destructor of the derived class will not be called, which can lead to resource leaks.