23

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)?

3
  • 3
    The curly-brackets are new in the C++11 standard, and used for something called uniform initialization. In many cases there's no difference though. Mar 25, 2016 at 1:50
  • Does initializing with parentheses -- i.e. sz(s) and elem(new double[s]) imply a constructor is being called in both cases?
    – George
    Mar 25, 2016 at 2:01
  • 1
    Neither int nor double* 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 as sz(s) or sz{s} (if s was 5) in your initialization list. Mar 25, 2016 at 2:08

1 Answer 1

16

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.

1
  • 4
    There is of course a difference. The latter is initialized first with a std::initializer_list and then taken in by the constructor. So you can have a different outcome e.g. with std::vector when having 2 parameters: like {1, 2} behaves different than (1, 2).
    – jaques-sam
    Nov 30, 2021 at 8:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.