virtual-bases/virtual-1.cc - Illustration of shared, virtual, base class A. | Lecture 5 - slide 20 : 40 Program 1 |
// Illustration of virtual base classes. #include <iostream> #include <string> using namespace std; class A { public: int a; A(): a(8){} A(int a): a(11){} }; class B : public virtual A { public: int b; B(): b(1){} }; class C : public virtual A { public: int c; C(): c(2){} }; class D : public B, public C { public: int d; D(): d(9){} // use default constructors of B and C }; int f(D &x){ cout << x.a << endl; // 8 - not ambiguous, only one a in x. cout << x.B::a << endl; // 8 cout << x.C::a << endl; // 8 cout << x.b << endl; // 1 cout << x.c << endl; // 2 cout << x.d << endl; // 9 } int main(){ D d; f(d); }