Initialization Order of Non-Static Data Members
In this scenario, we have two non-static data members, a and b, declared within the class X. A common question arises: in what order are these data members initialized when the constructor for X is invoked?
To answer this question, we turn to section 12.6.2 of the C Standard, which outlines the initialization order of class members:
5 Initialization shall proceed in the following order: -- First, and only for the constructor of the most derived class as described below, virtual base classes shall be initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes... -- Then, direct base classes shall be initialized in declaration order as they appear in the base-specifier-list... -- Then, nonstatic data members shall be initialized in the order they were declared in the class definition... -- Finally, the body of the constructor is executed...
Based on this rule, the order of initialization of a and b is determined solely by their placement within the class definition. Since a precedes b, it will be initialized first. This holds true regardless of any explicitly specified order of member initialization within the constructor body.
Therefore, in this case, the constructor of A will be called before the constructor of B when the constructor of X is invoked.
The above is the detailed content of What's the Initialization Order of Non-Static Data Members in C ?. For more information, please follow other related articles on the PHP Chinese website!