Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

What's the difference between () and {} when constructing objects?

I think {} should only support with initializer_list or an array, but when I run below snip, I confused.

#include <iostream>
using namespace std;
struct S {
    int v=0;
    S(int l) : v(l) {
    }
};


int main()
{
    S s1(12); // statement1
    S s2{12}; // statement2
    cout << s1.v << endl;
    cout << s2.v << endl;
}

statement1 is right because () is the basic grammar for constructing the object.

I expect the statement2 will be compiled failed. I think {} is only can be used for an array or initializer_list type. but the actual result is compiled perfectly without error.

what do I mis?

like image 636
David Avatar asked Feb 26 '26 15:02

David


1 Answers

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.

like image 139
songyuanyao Avatar answered Feb 28 '26 04:02

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!