+ 2

What's the advantage of member initializers?

I have got the impression that the following two ways to write a constructor lead to the same result. Is this really the case? If not, what is the advantage of one over the other, or when to use which? Classname(int x) {this->x = x;} Classname(int x): x{x} {} (I have just remembered that you can use the second version to initialize const members. But in a book I've read that we should always use the second version... but why?)

5th Apr 2019, 7:54 PM
HonFu
HonFu - avatar
1 Resposta
+ 3
Most of the time the result is the same, yea. It's a subtle difference, initialization vs assignment class T { public: T(){ std::cout << "construct "; } T( int ){ std::cout << "initialize "; } void operator=( int ){ std::cout << "assignment "; } }; // where x is type T Classname(int x) {this->x = x;} // Would print construct assignment Classname(int x): x{x} {} // Would print initialize So unless these functions do something completely different for some reason the result is the same. Using assignment is also less efficient as you can see, first the constructor is called and then it is assigned again. While when initializing it only happens once. The compiler can optimize that though, but don't count on it always. Secondly, assignment is illegal for const and reference variables as they must be initialized and you can't initialize an array with an assignment either.
5th Apr 2019, 8:15 PM
Dennis
Dennis - avatar