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.
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.