Consider the following code snippet from pg. 17 's A Tour of C++:
class Vector {
public:
Vector(int s) :elem{new double[s]}, sz{s} { } //construct a Vector
double& operator[](int i) { return elem[i]; } //element access: subscripting
int size() { return sz; }
private:
double* elem; // pointer to the elements
int sz; // the number of elements
};
Here I'm concerned about the member initializer list on the third line, where Stroustrup separates a colon from the two initializer statements elem{new double[s]}
and sz{s}
.
Question: Why here does he use curly braces (i.e., {..}
) to make these two initializer statements? I have seen elsewhere on the web people making initializer lists with parentheses, such that this could also (AFAIK) legally read elem(new double[s])
and sz(s)
. So is there a semantic difference between these two notations? Are there other ways one could initialize these variables (within the context of an initializer list)?
The form
Vector(int s) :elem(new double[s]), sz(s) { }
is correct in all versions of C++. The one with curly-braces, like
Vector(int s) :elem{new double[s]}, sz{s} { }
was introduced into the C++ standard in 2011, and is invalid in older standards.
In the context you ask about, there is no difference. However, there are other language and library features, also introduced into the 2011 standard, that rely on the second form and don't work with the first.
There are no other ways of initialising members of bases in initialiser lists of constructors. It is possible to assign to members in the body of constructors, but that is not initialiser syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With