Junior — Middle
Explain the purpose of a virtual destructor in the context of object-oriented programming.
sobes.tech AI
Answer from AI
A virtual destructor in C++ is used for proper resource cleanup when deleting an object through a pointer to the base class. If the base class has a virtual destructor, then deleting an object through a base class pointer will invoke the derived class's destructor, ensuring correct object destruction and preventing memory leaks.
Example:
class Base {
public:
virtual ~Base() { std::cout << "Base destructor\n"; }
};
class Derived : public Base {
public:
~Derived() { std::cout << "Derived destructor\n"; }
};
int main() {
Base* obj = new Derived();
delete obj; // will call Derived::~Derived first, then Base::~Base
}
Without a virtual destructor, calling delete through a base class pointer will only invoke the base class destructor, which can cause issues with resource cleanup in the derived class.