C++ initialization takes place in this order:
- Base classes, from left to right
- Member variables, in the order in which they are declared
The initialization of base classes from step 1 recursively takes the same steps. Therefore, all bases are fully constructed before any member variable initialization takes place, and before the body of the constructor begins execution.
Therefore, when the compiler encounters:
Two two;
First, Two::Two
begins execution, starting with the initializer list. All bases are initialized via the initialization list, even if you haven't written one or left out the initialization of a base class. So, the code that actually runs looks more like this:
Two::Two
:
One(),
test()
{
test = "text";
}
The initializer list is executed before the body of the constructor. Therefore, One
is completely constructed before the the body of Two::Two
begins execution.
In turn, One
looks like this:
One::One()
:
Base()
{
string test = "test";
}
And Base
is empty:
Base::Base()
{
}
So what happens when Two two;
is executed is:
Base
is constructed.One
is constructed- The automatic variable
test
is constructed, initialized, and destroyed in the context ofOne::One
Two::test
is default-initializedTwo::test
is assigned the value "text"
Note that some of this, especially steps 4 & 5 might get optimized by the compiler if it thinks it's safe to do so.