Sobes.tech
Junior — Middle

Is it possible to declare a destructor as virtual in a class?

sobes.tech AI

Answer from AI

Yes, in C++, a destructor can be declared virtual. This is important when you have a base class with virtual functions and derived classes, and you want to ensure the correct destructor is called when deleting an object through a pointer to the base class. If the destructor is not virtual, only the base class destructor will be called when deleting through a base class pointer, which can lead to resource leaks.

Example:

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

class Derived : public Base {
public:
    ~Derived() override { std::cout << "Derived destructor\n"; }
};

int main() {
    Base* obj = new Derived();
    delete obj; // Will call Derived::~Derived(), then Base::~Base()
}