Home >Backend Development >C++ >How Does C Initialize Non-Static Data Members?
Initialization Order of Non-Static Data Members
In C , when initializing an object, the order of initialization of non-static data members is a matter of concern. To understand this order, it's important to refer to the relevant section of the C Standard.
According to 12.6.2 of the C Standard, non-static data members are initialized in the order they appear in the class definition. This is regardless of the order in which member initializer lists appear within the class body.
Consider the following example:
class A {}; class B {}; class X { A a; B b; };
In class X, the order of initialization is A followed by B. This is because A is declared before B in the class definition. It doesn't matter if the order of member initializer lists within the constructor was different.
This initialization order ensures that base classes and member subobjects are destroyed in the reverse order of initialization. Therefore, B would be destroyed before A in the example above.
The above is the detailed content of How Does C Initialize Non-Static Data Members?. For more information, please follow other related articles on the PHP Chinese website!