2

I ended up on this page in the references.

I got somewhat confused with this example:

class X {
    int a, b, i, j;
public:
    const int& r;
    X(int i)
      : r(a) // initializes X::r to refer to X::a
      , b{i} // initializes X::b to the value of the parameter i
      , i(i) // initializes X::i to the value of the parameter i
      , j(this->i) // initializes X::j to the value of X::i
    { }
};

Is there any difference between using the bracketed initializer list syntax like b{x} and the traditional parenthesis syntax b(x)?

When should I use each one of them?

Henrique Barcelos
  • 7,670
  • 1
  • 41
  • 66
  • Apart from the obvious point that `{}` is not backward-compatible, you mean? ;-) – DevSolar Jul 29 '15 at 13:50
  • @DevSolar yes, for sure :) – Henrique Barcelos Jul 29 '15 at 13:51
  • i bet `{}` would work only with structures with public attributes. try it with a class Y instance, which has only private attributes. i bet it will fail. – Pierre Emmanuel Lallemant Jul 29 '15 at 13:52
  • You have to keep in mind that if your class Y has a constructor that takes a initializer_list as argument, and another one that takes a number, Y{5} will call the initializer_list's constructor, but Y(5), the other one. – Damián Montenegro Jul 29 '15 at 13:59
  • 1
    There are some differences between `b{x}` (which is a [direct-list-initialization](http://en.cppreference.com/w/cpp/language/list_initialization) and `b(x)` (which is a [direct-non-list-initialization](http://en.cppreference.com/w/cpp/language/direct_initialization), but I believe that the author of this example (who is @Cubbi) only wants to point out that both syntax are usable within the constructor initialization list. – cpplearner Jul 29 '15 at 14:00
  • 1
    @PierreEmmanuelLallemant, not, it works for private attributes too. – Henrique Barcelos Jul 29 '15 at 14:02

0 Answers0