20-CS-122-001 Computer Science II Spring 2012
Method Invocations in a Class Hierarchy

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

Prev      Next      Lectures      Source

// Virtual functions - look up the hierarchy if method not found at
// level entered.  Otherwise look down the hierarchy until reaching 
// the level at which the object was created.  This experiment defines
// a virtual function only at the top level in the hierarchy.

#include <iostream>
using namespace std;

class A {
public:
   void f() { cout << "A\n"; }
};

class B : public A {
public:
   void f() { cout << "B\n"; }
};

class C : public B {
public:
   virtual void f() { cout << "C\n"; }
};

class D : public C {
public:
   void f() { cout << "D\n"; }
};

class E : public D {
public:
   void f() { cout << "E\n"; }
};

int main() {
   A *a = new A();
   B *b = new B();
   C *c = new C();
   D *d = new D();
   E *e = new E();
   
   cout << "((A*)e)->f(): ";
   ((A*)e)->f();
   cout << "((A*)d)->f(): ";
   ((A*)d)->f();
   cout << "((A*)c)->f(): ";
   ((A*)c)->f();
   cout << "((A*)b)->f(): ";
   ((A*)b)->f();
   cout << "((A*)a)->f(): ";
   ((A*)a)->f();
   cout << "\n";

   cout << "((B*)e)->f(): ";
   ((B*)e)->f();
   cout << "((B*)d)->f(): ";
   ((B*)d)->f();
   cout << "((B*)c)->f(): ";
   ((B*)c)->f();
   cout << "((B*)b)->f(): ";
   ((B*)b)->f();
   cout << "\n";

   cout << "((C*)e)->f(): ";
   ((C*)e)->f();
   cout << "((C*)d)->f(): ";
   ((C*)d)->f();
   cout << "((C*)c)->f(): ";
   ((C*)c)->f();
   cout << "\n";

   cout << "((D*)e)->f(): ";
   ((D*)e)->f();
   cout << "((D*)d)->f(): ";
   ((D*)d)->f();
   cout << "\n";

   cout << "((D*)e)->f(): ";
   ((E*)e)->f();
   cout << "\n";
}

// Sample Output:  Same result as where virtuals defined at all levels
//   ((A*)d)->f(): D
//   ((A*)c)->f(): C
//   ((A*)b)->f(): B
//   ((A*)a)->f(): A
//
//   ((B*)d)->f(): D
//   ((B*)c)->f(): C
//   ((B*)b)->f(): B
//
//   ((C*)d)->f(): D
//   ((C*)c)->f(): C
//
//   ((D*)d)->f(): D