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 cited by the previous answer and, in addition, I show that the constructor of sof
is not called in the class scope execution, but just before that constructor is called, as shown in the output:
sof
tipo-default
sof-constr
tipo-int
But it is also possible to see the other case of the usefulness of the Member initializer lists which is the case with std::ostream& x
: this must be declared and initialized in the "same statement" for being reference (another case would be variables of type const
), so cannot be initialized in the scope of the constructor sof
.
Now you can vote for everything on the site too
– Maniero