A virtual base class calls an empty constructor in C ++ (C ++ 11)

Let's look at the following code:

class A{ protected: int _val; public: A(){printf("calling A empty constructor\n");} A(int val):_val(val){printf("calling A constructor (%d)\n", val);} }; class B: virtual public A{ public: B(){printf("calling B empty constructor\n");} B(int val):A(val){printf("calling B constructor (%d)\n", val);} }; class C: public B{ public: C(){printf("calling C empty constructor\n");} C(int val):B(val){printf("calling C constructor (%d)\n", val);} }; int main(void) { C test(2); } 

Output:

 calling A empty constructor calling B constructor (2) calling C constructor (2) 

Can someone explain to me why the class A constructor is called without any arguments? Additionally, how can I β€œfix” this behavior if I want class B to actually inherit from A? (If inheritance is not virtual - the sample works fine)

+7
source share
1 answer

In C ++ 03, this will be the same.

Virtual base constructors are always called from the final leaf class. If you want something other than the default constructor for A when you instantiate C, you must also specify it in the constructor of class C.

 C(int val): A(val), B(val) {printf("calling C constructor (%d)\n", val);} 
+10
source

All Articles