Initializing brackets for a class with a virtual function

There is this code:

struct A { int x; void f() {} }; struct B { int y; virtual void f() {} }; A a = {2}; //B b = {3}; error: no matching constructor for initialization of 'B' int main() { return 0; } 

Why does initialization for variable a work, but not for variable b ?

+7
source share
1 answer

A is an aggregate and therefore may have parenthesis initialization, and B not, since it has a virtual method.

8.5.1 Units

An aggregate is an array or class (section 9) without constructors provided by the user (12.1), without brackets or equal initializers for non-static data members (9.2), no private or protected non-static data (section 11), no base classes (section 10 ) and there are no virtual functions (10.3).

+10
source

All Articles