I deliberately create the following code to let me easily present the question.
Question> What is the initialization order of all variables?
#include <iostream>
int iGlobal = 10;
class A {
public:
A(int _a) : m_a_a(_a) {}
private:
int m_a_a;
};
class B : public A
{
public:
B() : m_b_b(40), A(20), m_b_a(30) {}
private:
static int m_b_static_a;
int m_b_a;
int m_b_b;
int m_b_c; // this variable is NOT initialized in the B::B() initialization list
static int m_b_static_b;
};
int B::m_b_static_a = 11;
int B::m_b_static_b = 12;
int main(void)
{
B b;
return 0;
}
First, I list all variables as follows:
iGlobal, m_a_a, m_b_static_a, m_b_a, m_b_b, m_b_c, m_b_static_b
Here is what I think I am right.
m_a_a < m_b_a < m_b_b < m_b_c (i.e. X < Y iff X is initialized early than Y)
m_b_static_a < m_b_static_b
Rule1> C++ guarantees that variables in compilation unit (.cpp file) are initialised in order of declaration.
Rule2> The order listed in the initialized list doesn’t control the order of initialization.
I have problems to order among the global variable, static variable and non-static variable.
Within a compilation unit, globals are initialised in the same order they’re declared. However, the order is unspecified across different compilation units (see What’s the “static initialization order fiasco”?).
Class initialisation order:
Members initialisation respects the declaration order, regardless the order used in the initilisation list.
Having
class C : public A, public B, initialiasesA, thenB, thenC. And their destruction occurs in the inverse order.NOTE: Virtual base classes do not respect the order mentioned above.
Quoting §12.6.2/5 from the C++03 Standard:
Concluding, the order will be: