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

// No virtual functions - look up the hierarchy if method not found at
// level entered.  Otherwise invoke method at entry level even if the
// object was originally created from a class lower 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:
   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:  Invoke function at level entered
//   ((A *)d)->f(): A
//   ((A *)c)->f(): A
//   ((A *)b)->f(): A
//   ((A *)a)->f(): A
//
//   ((B *)d)->f(): B
//   ((B *)c)->f(): B
//   ((B *)b)->f(): B
//
//   ((C *)d)->f(): C
//   ((C *)c)->f(): C
//
//   ((D *)d)->f(): D