Given some class having some data members that have meaningful default initializers,
class C {
int m1 = 42;
C2 m2 = 99;
C2 m3 = { 99 };
⋮
};
Class C2
has a constructor that takes 1 argument, and may not be locally the resulting value of the object, nor a container-like thing where I'm giving it one of the things it will be holding.
For variables (as opposed to class data members) the difference between "a parameter used for something in the initialization" vs "holds this value" is normally exemplified by the case of std::vector.
std::vector<int> t1 (5); // 5 is specific to initialization in some manner, not the resulting value.
std::vector<int> t2 { 5 }; // 5 is (one of) the values contained in t2.
Now in the in-class member syntax, m2
looks like m1
and seems to convey that m2 will hold a value equivalent to 99. But, that's not the case: the constructor argument might be choosing a mode or otherwise have a domain that's different from the get/set of any typical property of m2
.
So, I look at m3
as being “different from that” and general to the case of needing multiple constructor arguments. But now I see that this is exactly the opposite of how I use that syntax in regular initialized definitions: it normally specifies the value, and if the class distinguished the two forms as with vector, it would in fact call the wrong one from what I mean.
So, what is the current wisdom for the best practice in writing in-class default values? Any gotcha's to know about in actual semantics, beyond the self-documentation and clarity issues? This answer is about whether one should put initializers in the class with the specific member, and I agree with this in that it's good to do when it's always the same and doesn't depend on any argument. I'm asking about the choice of which syntax to use.
(P.S. The same thing shows up in return types and parameter values in function calls where I don't want to mention the type manually: return {5};
is better than return C2(5);
in that it avoids the type name, but it forces the use of this form of initialization syntax, which might be contrary to the form I would have used for clarity or even correctness in the case of a definition.)