Home >Backend Development >C++ >What's the Order of Constructor and Destructor Calls in C Inheritance?
Order of Constructor and Destructor Calls in Inheritance
When defining inherited classes, it's crucial to understand the sequences in which constructors and destructors are invoked. Consider the following example:
struct A { A() { cout << "A() C-tor" << endl; } ~A() { cout << "~A() D-tor" << endl; } }; struct B : public A { B() { cout << "B() C-tor" << endl; } ~B() { cout << "~B() D-tor" << endl; } A a; };
Construction Order:
Thus, the order of construction is:
Destruction Order:
Destructors are invoked in the reverse order of construction:
The order of destruction is:
Initializer List:
Even if no explicit initializer list is defined in B, a default initialization list is automatically generated by the compiler. This list initializes the base class (A) and the member field (a) using their default constructors.
In conclusion, the order of constructor and destructor calls in inheritance follows specific rules: constructors initialize base classes first, then member fields, and finally the derived class. Destructors invoke the cleanup process in reverse order. Understanding these rules is essential for writing robust code when using inheritance.
The above is the detailed content of What's the Order of Constructor and Destructor Calls in C Inheritance?. For more information, please follow other related articles on the PHP Chinese website!