Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Default constructor called in virtual inheritance?

I don't understand why in the following code, when I instanciate an object of type daughter, the default grandmother() constructor is called ?

I thought that either the grandmother(int) constructor should be called (to follow the specification of my mother class constructor), or this code shouldn't compile at all because of the virtual inheritance.

Here compiler silently calls grandmother default constructor in my back, whereas I never asked for it.

#include <iostream>  class grandmother { public:     grandmother() {         std::cout << "grandmother (default)" << std::endl;     }     grandmother(int attr) {         std::cout << "grandmother: " << attr << std::endl;     } };  class mother: virtual public grandmother { public:     mother(int attr) : grandmother(attr) {         std::cout << "mother: " << attr << std::endl;     } };  class daughter: virtual public mother { public:     daughter(int attr) : mother(attr) {         std::cout << "daughter: " << attr << std::endl;     } };  int main() {   daughter x(0); } 
like image 617
Simon Desfarges Avatar asked Mar 28 '12 12:03

Simon Desfarges


People also ask

Why default constructor is needed in inheritance?

The default constructor in the Person class is not inherited by Employee and therefore a default constructor must be provided in Employee, either automatically by the compiler or coded by the developer. Note that the compiler will also generate a call to the base class default constructor.

Why is it called a default constructor?

This constructor is called the default constructor because it is run "by default;" if there is no initializer, then this constructor is used. The default constructor is used regardless of where a variable is defined.

Is default constructor virtual?

Trivial default constructorT has no virtual base classes.

Why is virtual base class constructor called first?

In the case where a class has one or more base classes, the base class constructors are invoked before the derived class constructor. The base class constructors are called in the order they are declared.


1 Answers

When using virtual inheritance, the virtual base class's constructor is called directly by the most derived class's constructor. In this case, the daughter constructor directly calls the grandmother constructor.

Since you didn't explicitly call grandmother constructor in the initialization list, the default constructor will be called. To call the correct constructor, change it to:

daugther(int attr) : grandmother(attr), mother(attr) { ... } 

See also This FAQ entry.

like image 173
interjay Avatar answered Oct 03 '22 02:10

interjay