我不明白为什么在下面的代码中,当我实例化一个类型为object的对象时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);
}