What’s the difference between parentheses and braces in c++ when constructing objects

For S, they have the same effect. Both invoke the constructor S::S(int) to initialize the objects.

S s2{12}; is regared as list initialization (since C++11); S is not an aggregate type and not std::initializer_list, and has no constructor taking std::initializer_list, then

If the previous stage does not produce a match, all constructors of T participate in overload resolution against the set of arguments that consists of the elements of the braced-init-list, with the restriction that only non-narrowing conversions are allowed.

and you thought that

I think {} is only can be used for an array or initializer_list type.

This is not true. The effect of list-initialization is that, e.g. if S is an aggregate type, then aggregate initialization is performed; if S is a specialization of std::initializer_list, then it’s initialized as a std::initializer_list; if S has a constructor taking std::initializer_list, then it will be preferred to be used for initialization. You can refer to the page linked for more precise details.

PS: S s1(12); performs direct initialization.

Leave a Comment