Source of inherit3..cpp


  1: /** @file inherit3.cpp */

  3: #include <iostream>
  4: using namespace std;

  6: class Base
  7: {
  8: public:
  9:     int i;
 10:     Base(int x) { i = x; }
 11:     virtual void display()
 12:     {
 13:         cout << "\nUsing Base version of display(): ";
 14:         cout << i;
 15:         cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 16:     }
 17: };


 20: class Derived1 : public Base
 21: {
 22: public:
 23:     Derived1(int x) : Base(x) {}
 24:     //Note that Derived1 overrides the display() in Base
 25:     virtual void display()
 26:     {
 27:         cout << "\nUsing Derived1's version of display(): ";
 28:         cout << i*i;
 29:         cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 30:     }
 31: };


 34: class Derived2 : public Base
 35: {
 36: public:
 37:     Derived2(int x) : Base(x) {}
 38:     //Note that Derived2 does *not* override the display() in Base
 39: };


 42: int main()
 43: {
 44:     cout << "\nThis program illustrates that \"virtual functions are "
 45:         "hierarchical\", which is a\nfancy way of saying that if a "
 46:         "virtual function is *not* overridden in a derived\nclass, the "
 47:         "runtime will search up the hierarchy to find a function to call "
 48:         "in\nplace of the \"missing\" function in the current object.";
 49:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 51:     Base *p;
 52:     Base baseObject(10);
 53:     Derived1 derived1Object(10);
 54:     Derived2 derived2Object(10);

 56:     p = &baseObject;
 57:     p->display(); //Use Base's display()

 59:     p = &derived1Object;
 60:     p->display(); //Use Derived1's display()

 62:     p = &derived2Object;
 63:     p->display(); //Use Base's display()
 64: }