Home >Backend Development >C++ >How are Constructors and Destructors Called in C Inheritance?
Order of Constructor and Destructor Calls in Inheritance
In object-oriented programming with inheritance, understanding the order of constructor and destructor calls is crucial. This becomes particularly important when dealing with multiple base classes and object compositions.
Consider the following class hierarchy:
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; };
In the main function:
int main() { B b; }
Here are the rules governing the order of constructor and destructor calls in this inheritance hierarchy:
Constructor Calls:
Destructor Calls:
The order of destructor calls is the reverse of the constructor call order:
Default Initialization List:
Even without an explicitly defined initialization list, the member field will be initialized before the derived class constructor is called. In this case, a would be initialized to the default constructor of A.
Therefore, the expected output for the code in the main function would be:
A() C-tor A() C-tor B() C-tor ~B() D-tor ~A() D-tor ~A() D-tor
The above is the detailed content of How are Constructors and Destructors Called in C Inheritance?. For more information, please follow other related articles on the PHP Chinese website!