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)?
sz(s)
andelem(new double[s])
imply a constructor is being called in both cases?int
nordouble*
have constructors, so how could a constructor be called. It's simply initialization. You would not expect e.g.int sz = 5
to call a constructor? It's doing just the same thing assz(s)
orsz{s}
(ifs
was5
) in your initialization list.