Back to slide -- Keyboard shortcut: 'u'  previous -- Keyboard shortcut: 'p'                virtual-bases/virtual-problem-variant.cc - Forcing use of a constructor in a virtual base class.Lecture 5 - slide 20 : 40
Program 4

// Solution. Now enforcing use of particular A constructors in the D constructor.

#include <iostream>
#include <string>

using namespace std;

class A {
public:
  int a;
  A(): a(9){}
  A(int a): a(a){}
};

class B : public virtual A {
public:
  int b;
  B(): A(5), b(1){}                 
};

class C : public virtual A {
public:
  int c;
  C(): A(7), c(2){}                 
};

class D : public B, public C {
public:
  int d;
  D(): C(), B(), A(8), d(9){}       // Notice the initialization of the virtual A object part here: A(8).
};


int f(D &x){
  cout << x.a << endl;     // 8     // The A(int) constructor is forced in the D-constructor.
  cout << x.B::a << endl;  // 8     // See page 634-635 of The C++ Programming Language (4ed).
  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);
}