Search code examples
c++c++11list-initialization

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.


Solution

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