Home >Backend Development >C++ >How are member constructors and destructors called in C inheritance and aggregation?
Order of Member Constructor and Destructor Calls
In C , the order of member constructor and destructor calls is a fundamental aspect of object initialization and destruction. It ensures proper initialization and cleanup of class members, especially in situations involving inheritance and aggregation.
Consider the following program:
#include <iostream> using namespace std; struct A { A() { cout << "A::A" << endl; } ~A() { cout << "A::~" << endl; } }; struct B { B() { cout << "B::B" << endl; } ~B() { cout << "B::~" << endl; } }; struct C { C() { cout << "C::C" << endl; } ~C() { cout << "C::~" << endl; } }; struct Aggregate { A a; B b; C c; }; int main() { Aggregate a; return 0; }
When executed, this program produces the following output:
A::A B::B C::C C::~ B::~ A::~
This output demonstrates that the member constructors are called in the order of declaration, and the member destructors are called in the reverse order of declaration.
The C Standard guarantees this order under the following conditions:
In this example, the Aggregate class contains members a of type A, b of type B, and c of type C. When the Aggregate constructor is called, the members are initialized in the order a, b, and c. Correspondingly, when the Aggregate destructor is called, the members are destroyed in the reverse order, c, b, and a.
Understanding the order of member constructor and destructor calls is crucial for correct object lifetime management in C , especially when working with inheritance and complex class structures.
The above is the detailed content of How are member constructors and destructors called in C inheritance and aggregation?. For more information, please follow other related articles on the PHP Chinese website!