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?
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
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.
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 };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With