#include <iostream> using namespace std; class base { public: int i; }; class derived1 : public base {}; class derived2 : public base {}; class derived3 : public derived1, public derived2 {}; int main() { derived3 test; cout << test.i; // コンパイルエラー }
baseを継承したderived1とderived2の両方を多重継承したderived3では、iを参照した場合、derived1かderived2のどちらのiかあいまいになってしまうのでコンパイルエラーとなる。
この場合、仮想基本クラスを使って解消することができる。
継承するときにvirtualを付けると基本クラスのオブジェクトが1つしか持たないようになる。
#include <iostream> using namespace std; class base { public: int i; }; class derived1 : virtual public base {}; class derived2 : virtual public base {}; class derived3 : public derived1, public derived2 {}; int main() { derived3 test; cout << test.i; }