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.

#include <iostream>
using namespace std;

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

class B : public A {
 public:
   virtual 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"; }
};

int main() {
   A *a = new A();
   B *b = new B();
   C *c = new C();
   D *d = new D();
   
   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 *)d)->f(): ";
   ((B *)d)->f();
   cout << "((B *)c)->f(): ";
   ((B *)c)->f();
   cout << "((B *)b)->f(): ";
   ((B *)b)->f();

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

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

// Sample Output:  Look down the hierarchy
//   ((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