Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Brace initialization for class with virtual function

Tags:

c++

c++11

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?

like image 887
scdmb Avatar asked May 16 '13 19:05

scdmb


People also ask

What is brace initialization?

If a type has a default constructor, either implicitly or explicitly declared, you can use brace initialization with empty braces to invoke it. For example, the following class may be initialized by using both empty and non-empty brace initialization: C++ Copy.

Can we create object of class having virtual function?

Virtual Functions in Derived Classes in C++ When you use a pointer or a reference to the base class to refer to a derived class object, you can call a virtual function for that object and have it run the derived class's version of the function.

What is uniform initialization?

Uniform initialization is a feature in C++ 11 that allows the usage of a consistent syntax to initialize variables and objects ranging from primitive type to aggregates. In other words, it introduces brace-initialization that uses braces ({}) to enclose initializer values.

What is aggregate type C++?

Formal definition from the C++ standard (C++03 8.5. 1 §1): An aggregate is an array or a class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10), and no virtual functions (10.3).


1 Answers

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).

like image 87
juanchopanza Avatar answered Nov 15 '22 13:11

juanchopanza