1

I was looking at the cppreference for constructors and I came across this:

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
    { }
};

When constructing for b and i, why do they use different brackets? The first one uses {} and the second one uses ()

Can someone explain this to me? I tried using both and I can't find a difference.

feverdreme
  • 467
  • 4
  • 12
  • 2
    https://en.cppreference.com/w/cpp/language/initialization `{}` can be used for value initialization and list initialization. `()` is used for direct initialization. – Thomas Sablik Oct 31 '20 at 20:20
  • There's not that many circumstances where they differ, and the differences tend to be fairly specific to each case. In addition to the link Thomas provided, there's a good discussion [here](https://stackoverflow.com/questions/18222926/why-is-list-initialization-using-curly-braces-better-than-the-alternatives). It's particularly relevant when initializing containers. – Nathan Pierson Oct 31 '20 at 20:21
  • One difference is {} will restrict 'the most vexing parse'. – SpongeBob Oct 31 '20 at 21:10

2 Answers2

1

In your example there is no difference, you can use either of them, but, there exist some differences in some other context, for example, you can use curly braces to initialize a vector see below program.

#include<iostream>
#include<vector>

int main(){

    std::vector<int> first(12,3,5,6);   // Compile time error
    std::vector<int> second{12,3,5,6};  // Ok 

    return 0;
}

Hope, this helps you understand the difference, for more information, you should check the link mentioned by @Thomas Salik. Link.

dukeforever
  • 298
  • 1
  • 7
0

When constructing for b and i, why do they use different brackets?

Because whoever wrote it chose to do so. Why they chose what they did can only be answered by the author.

I can't find a difference.

There is no difference in this case.

There could be a difference when initialising class types or when implicit conversions are involved.


The use of a reference member is usually a bad idea. A reference member referring to another member is probably always a bad idea.

eerorika
  • 232,697
  • 12
  • 197
  • 326