Home >Backend Development >C++ >What's the Order of Construction and Destruction in C Inheritance?
Order of Construction and Destruction in Inheritance
Consider the following class hierarchy:
struct A { A() { std::cout << "A() C-tor" << std::endl; } ~A() { std::cout << "~A() D-tor" << std::endl; } }; struct B : public A { B() { std::cout << "B() C-tor" << std::endl; } ~B() { std::cout << "~B() D-tor" << std::endl; } A a; };
When an instance of B is created (as in int main() { B b; }), the construction and destruction order follows specific rules:
Construction Order:
This translates to the following call order:
Destruction Order:
This results in the following destruction order:
Therefore, the construction order starts with the base class, proceeds to the member fields, and ends with the derived class. The destruction order is the reverse of the construction order.
The above is the detailed content of What's the Order of Construction and Destruction in C Inheritance?. For more information, please follow other related articles on the PHP Chinese website!