Junior — Middle
What is the sequence of object destruction method calls when an object is destroyed in a programming language?
sobes.tech AI
Answer from AI
In C++, when destroying an object, the sequence of destructor calls depends on the inheritance hierarchy:
- The destructor of the most derived (child) class is called first.
- Then, the destructors of the base classes are called in the reverse order of their declaration.
If the destructor is virtual, the destructor of the derived class is called even if the object is deleted through a base class pointer.
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 output:
// Derived destructor
// Base destructor
}
Thus, the destructor of Derived is called first, then the Base destructor.