为什么叫缺省构造函数虚继承?

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

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.