I would like to complete the previous answer with the following code:
#include <iostream>
class Tipo {
int x;
public:
Tipo() {
x = 0;
std::cout << "tipo-default\n";
}
Tipo(int p) {
x = p;
std::cout << "tipo-int\n";
}
};
class sof {
std::ostream& x;
Tipo teste;
public:
sof(int t) : x(std::cout << "sof\n") {
std::cout << "sof-constr\n";
teste = Tipo(t);
}
};
int main() {
sof s(10);
return 0;
}
Here I show the case quoted by the previous answer and, furthermore, I show that the constructor of sof
is not called in the execution of the class scope, but just before this constructor is called, as shown in the output: p>
sof
tipo-default
sof-constr
tipo-int
But it is also possible to see the other case of the member initializer lists which is the case of std::ostream& x
: this must be declared and initialized in the "same statement" because it is a reference if it would be variables of type const
), then it can not be initialized in the constructor scope of sof
.