Why is the default constructor called virtual inheritance?

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

I thought that either the grandmother(int) constructor should be called (to follow the specifications of my mother class constructor), or this code should not be compiled at all due to virtual inheritance.

Here, the compiler silently calls the 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); } 
+62
c ++ inheritance virtual-inheritance
Mar 28 2018-12-12T00:
source share
1 answer

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

Since you did not explicitly call the grandmother constructor in the initialization list, the default constructor is called. To call the correct constructor, change it to:

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

See also This FAQ section .

+66
Mar 28 2018-12-12T00:
source share



All Articles