sanjivgupta
sanjivgupta

Reputation: 456

Empty initializer list as argument doesn't call default constructor

The following code

class A {
public:
    A() {} // default constructor
    A(int i) {} // second constructor
};
int main() {
    A obj({});
}

calls the second constructor. Probably the empty initializer_list is treated as one argument and is converted to int. But when you remove the second constructor from the class, it calls the default constructor. Why?

Also, I understand why A obj { {} } will always call a constructor with one argument as there we are passing one argument which is an empty initializer_list.

Upvotes: 6

Views: 1918

Answers (2)

Praetorian
Praetorian

Reputation: 109089

The presence of the parentheses surrounding the braces in A obj({}); indicates the single argument constructor will be called, if possible. In this case it is possible because an empty initializer list, or braced-init-list, can be used to value initialize an int, so the single argument constructor is called with i=0.

When you remove the single argument constructor, A obj({}); can no longer call the default constructor. However, the {} can be used to default construct an A and then the copy constructor can be called to initialize obj. You can confirm this by adding A(const A&) = delete;, and the code will fail to compile.

Upvotes: 5

n.caillou
n.caillou

Reputation: 1342

It's because the {} in A obj({}); ends up being interpreted as of type int. So the code ends up being similar to A obj(0);.

Upvotes: 0

Related Questions