Junior — Middle
Why is it important to declare a virtual destructor in the base class when using inheritance?
sobes.tech AI
Answer from AI
If the destructor is not declared virtual in the base class, deleting an object of the derived class through a pointer to the base class will only call the base class destructor. This can lead to resources allocated in the derived class not being properly released, which may cause memory leaks and other errors. Declaring the destructor as virtual ensures that destructors of all levels are called and resources are correctly freed.
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(), then Base::~Base()
}