Initialization Order of Non-Static Data Members in C
When creating a new instance of a class with non-static data members, the order in which they are initialized is crucial for proper object construction.
In this scenario, let's consider the following code:
class A {}; class B {}; class X { A a; B b; };
The question arises: when the constructor of class X is invoked, which constructor (A or B) is called first? Does their position within the class definition determine the order?
According to the C Standard, section 12.6.2, the initialization order is as follows:
Therefore, in the provided code, the non-static data members a and b are initialized in the order they are declared, which is a first followed by b. The constructor of A will be called before the constructor of B.
In summary, the order of initialization for non-static data members is determined by their declaration order within the class definition, not by their placement within the constructor body.
The above is the detailed content of What's the Initialization Order of Non-Static Data Members in C Classes?. For more information, please follow other related articles on the PHP Chinese website!