Just a simple question.

Hello!

I'd like to ask you guys what's the difference between these two notations(Shown below).
Sorry for the dumb question, I'm kinda new in C++.


1
2
  int test1(2);
  int test2{2};
In my opinion both of them are correct and do the same thing, correct me if I'm wrong.
Last edited on
closed account (LA48b7Xj)
The second example doesn't allow narrowing, which means a conversion with a loss of information. So for example you could write 4.5 in test1 but for test2 that would be a compile error.
http://en.cppreference.com/w/cpp/language/list_initialization

The long and short of it is, as Krako said, it won't allow narrowing conversions. So:

1
2
3
4
5
6
const double pi{3.1415};

int sliced_pi = pi; //Fine; value is 3
int also_sliced_pi(pi); //Same as above

int unsliced_pi{pi}; //Not fine; narrowing conversion your compiler (hopefully) catches 


Of course in all of the above, your compiler will (again, hopefully) warn you for the first two definitions, but assuming said compiler is up-to-date, it will fail at build and generate a compiler error for the last definition.
Topic archived. No new replies allowed.