I am reading about order of constructor's initialization in the C++ Super-FAQ from the web site The C++ Programming Language. There the following code is presented.
#include <iostream>
class Y {
public:
Y();
void f();
};
Y::Y() { std::cout << "Initializing Y\n"; }
void Y::f() { std::cout << "Using Y\n"; }
class X {
public:
X(Y& y);
};
X::X(Y& y) { y.f(); }
class Z {
public:
Z();
protected:
X x_;
Y y_;
};
Z::Z()
: y_()
, x_(y_)
{ }
int main()
{
Z z;
return 0;
}
The printed sequence from this code is:
Using Y
Initializing Y
Well, I just can not realize how this printing sequence is possible since in the constructor of class Z the instance y_ of Y class is first instanciated for then the instance x_ of X class be so. In other words, how can the printed order be possible which is close related with the used method order if to use the method Y::f() first I need to instanciate one Y which would certantly call its constructor and the print routine std::cout << "Initializing Y\n";.