20-CS-122-001 Computer Science II Spring 2012
Multiple Inheritance

Virtual functions, classes, inheritance, lists, queues, stacks, applications

Source
#include <iostream.h>

#include 
using namespace std;

class A {
public:
  virtual char f() { return 'A'; }
  virtual char h() { return 'A'; }
  char g() { return 'A'; }
  char tf() { return f(); }
  char tg() { return g(); }
};

class B {
public:
  virtual char f() { return 'B'; }
  virtual char h() { return 'B'; }
  char g() { return 'B'; }
  char tf() { return f(); }
  char tg() { return g(); }
};

class C : public A {
public:
  char f() { return 'C'; }
  char g() { return 'C'; }
  virtual char h() { return 'C'; }
};

class D : public B {
public:
  char f() { return 'D'; }
  char g() { return 'D'; }
  virtual char h() { return 'D'; }
};

class E : public C, public D {
public:
  char h() { return 'E'; }
};

class F : public D, public C {
public:
  char h() { return 'F'; }
};

int main() {
   E *e = new E;
   F *f = new F;

//   e->f(),   // ambiguous going up the hierarchy
   cout << ((A*)e)->f() << " ";  // C
   cout << ((B*)e)->f() << " ";  // D
//   e->g(),   // ambiguous going up the hierarchy
   cout << ((A*)e)->g() << " ";  // A
   cout << ((B*)e)->g() << " ";  // B
   cout << ((A*)e)->h() << " ";  // E
   cout << ((B*)e)->h() << " ";  // E
   cout << ((A*)f)->h() << " ";  // F
   cout << ((B*)f)->h() << " ";  // F
   cout << ((C*)f)->h() << " ";  // F
   cout << ((D*)f)->h() << " ";  // F
   // f->tf(),     // ambiguous
   // f->tg(),     // ambiguous
   // e->tf(),     // ambiguous
   // e->tg());    // ambiguous
   cout << ((A*)e)->tf() << " "; // C
   cout << ((A*)e)->tg() << " "; // A
   cout << ((B*)f)->tf() << " "; // D
   cout << ((B*)f)->tg() << " "; // B

   cout << ((B*)e)->tf() << " "; // D
   cout << ((B*)e)->tg() << " "; // B
   cout << ((A*)f)->tf() << " "; // C
   cout << ((A*)f)->tg() << " "; // A
   cout << "\n";
}

/* Sample output
C D A B E E F F F F C A D B D B C A
*/