Search code examples
c++inheritancestructinitializer-list

Initializer list for struct deriving from class (C++)


Can you tell me what is wrong in the following example? I am using C++17, where I thought the following should be supported.

class Base {
public:
    virtual ~Base() = default;
};

struct Derived : public Base {
    int m1;
};

int main() {
    /* Results in a compilation error 
     * error C2440: 'initializing': cannot convert from 'initializer list' to 'Derived'
     * message : No constructor could take the source type, or constructor overload resolution was ambiguous */
    Derived d{ {},1 };
    return 0;
}

Solution

  • It does not work because Derived is not an aggregate since it has a base class with virtual members.

    The code compiles and runs when removing the virtual destructor in Base and using C++17.

    If Base requires a virtual destructor, Derived can implement a custom constructor allowing initialization using curly brackets.

    class Base {
    public:
        virtual ~Base() = default;
    };
    
    struct Derived : public Base {
        Derived(int m): m1(m) {}
        int m1;
    };
    
    int main() {
        Derived d{ 1 };
        return 0;
    }