Junior — Middle
When deleting an object through a pointer to a base class with a virtual destructor, how are destructors called in the inheritance chain?
sobes.tech AI
Answer from AI
If the base class declares a virtual destructor, then when deleting an object through a pointer to the base class, a chain of destructors is called starting from the most derived class and up the inheritance hierarchy to the base. This guarantees the correct release of resources allocated in derived classes.
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* ptr = new Derived();
delete ptr; // Will call Derived::~Derived(), then Base::~Base()
}
Without a virtual destructor, calling delete through a pointer to the base class will lead to undefined behavior and, as a rule, will not call the destructor of the derived class.