'Brace Initialize struct with virtual functions

Brace initialization

        struct A
        {
            int a;
            int b;
            void foo(){}
        };

        A a{1, 2};

It works fine. But if change foo to a virtual function, It will not compile with error,

Error C2440 'initializing': cannot convert from 'initializer list' to

I find this,

An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).

But what's the reason behind it?



Solution 1:[1]

There isn't a way. like in this text you mentioned

An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).

this means that a class/struct or an array that has

  • no user-provided constructors
  • no private or protected non-static data members
  • no base classes
  • and no virtual functions

is an aggregate. and only an aggregate can have brace initialization. so in this case, your struct has a virtual function that violates one of the laws above and makes it a non-aggregate.

I don't know why this is the case.

I guess that if your struct is similar to the struct in c then your struct would work.

so like Hassan's answer, you should use a parameterized constructor instead.

Solution 2:[2]

Why don't you use a parameterized constructor with virtual void foo() {}

struct A
{
    int a;
    int b;
    A(int a, int b)
    {
        this->a = a;
        this->b = b;
    }
    virtual void foo() {}
};
A a{ 1, 2 }; 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Hassan