我不明白为什么在下面的代码中,当我实例化一个类型的对象时daughter
,会调用默认grandmother()
构造函数?
我认为grandmother(int)
应该调用构造函数(以遵循我的mother
类构造函数的规范),或者由于虚拟继承,这段代码根本不应该编译。
这里编译器grandmother
在我背后默默地调用默认构造函数,而我从未要求过它。
#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);
}