Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 343
Zhang Avatar asked Jul 03 '26 17:07

Zhang


2 Answers

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.

like image 107
silver takana Avatar answered Jul 05 '26 13:07

silver takana


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 }; 
like image 44
Hassan Avatar answered Jul 05 '26 12:07

Hassan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!