Search code examples
c++constructorcopy-constructor

Class Initializer list does not work with copy constructor


I have this class A with one variable, initializing variables using initializer list works totally fine, if no copy constructor is present.

class A {
    public:
    int x;
};

int main()
{
    A a = {2};
    printf("Hello World");

    return 0;
}

However if I do have a copy constructor inside the class, I am getting an error

main.cpp:23:13: error: could not convert ‘{2}’ from ‘’ to ‘A’
     A a = {2};

Code :

class A {
    public:
    int x;
    A(A& v)
    {
        printf("Copied");
    }
};

int main()
{
    A a = {2};
    printf("Hello World");

    return 0;
}

Why is it so?


Solution

  • The user-declared constructor A::A(A&) makes A not an aggregate, then it can't be aggregate-initialized from brace-init-list like {2} again.

    You can add a constructor taking int, e.g.

    class A {
        public:
        int x;
        A(int x) : x(x) {}
        A(const A& v)
        {
            printf("Copied");
        }
    };
    

    Then

    A a = {2}; // list-initialize a from {2} by constructor A::A(int)
    

    BTW: Copy constructor takes const T& conventionally.