Why is Default constructor called in virtual inheritance?

江枫思渺然 提交于 2019-11-26 03:07:28

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/9907722/why-is-default-constructor-called-in-virtual-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!