10

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 initialization for variable a works but not for variable b?

Syntactic Fructose
  • 17,149
  • 19
  • 87
  • 170
scdmb
  • 14,431
  • 20
  • 79
  • 125
  • 1
    Brace initialization only works for POD types; making your method virtual makes it non-POD – antlersoft May 16 '13 at 19:25
  • 2
    [What are Aggregates and Pods and how/why they are special](http://stackoverflow.com/questions/4178175/what-are-aggregates-and-pods-and-how-why-are-they-special) – Armen Tsirunyan May 16 '13 at 19:40

1 Answers1

12

A is an aggregate, and so can have brace initialization, and B isn't, since it has a virtual method.

8.5.1 Aggregates

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

juanchopanza
  • 216,937
  • 30
  • 383
  • 461