Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual baseclass calls empty constructor in C++ (C++11)

Lets 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);
}

The output is:

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

Could somebody explain to me why the A class constructor is called without any arguments? Additional how can I "fix" this behaviour if I want the B class to inherit virtually from A? (If the inheritance is not virtual - the sample works fine)

like image 872
Wojciech Danilo Avatar asked Jun 29 '13 13:06

Wojciech Danilo


People also ask

Can we call a virtual function from constructor?

You can call a virtual function in a constructor, but be careful. It may not do what you expect. In a constructor, the virtual call mechanism is disabled because overriding from derived classes hasn't yet happened. Objects are constructed from the base up, “base before derived”.

Which is also called as a virtual constructor?

Virtual Constructor in C++The virtual mechanism works only when we have a base class pointer to a derived class object. In C++, the constructor cannot be virtual, because when a constructor of a class is executed there is no virtual table in the memory, means no virtual pointer defined yet.

What is constructor and virtual function can we call virtual function in a constructor?

You can call a virtual function in a constructor. The Objects are constructed from the base up, “base before derived”.

Can constructor be pure virtual C++?

Pure virtual functions must not be called from a C++ constructor.


1 Answers

In c++03 it'd be the same.

Virtual base constructors are always called from the final leaf class. If you want something else than the default constructor for A when instantiating a C, you have to specify it in the constructor of class C too.

C(int val): A(val), B(val) {printf("calling C constructor (%d)\n", val);}
like image 185
Yohan Danvin Avatar answered Sep 20 '22 07:09

Yohan Danvin