Source of inherit1.cpp


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

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

  6: class Base
  7: {
  8: public:
  9:     void setX(int i) { x = i; }
 10:     int getx()       { return x; }
 11: private:
 12:     int x;
 13: };


 16: class Derived : public Base
 17: {
 18: public:
 19:     void setY(int i) { y = i; }
 20:     int getY()       { return y; }
 21: private:
 22:     int y;
 23: };


 26: int main()
 27: {
 28:     cout << "\nThis program illustrates use of the same pointer to point "
 29:         "first at an object of\na base class, and then at an object of a "
 30:         "class derived from that base class.";
 31:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 33:     Base *p;               //A pointer to Base type
 34:     Base baseObject;       //An object of Base type
 35:     Derived derivedObject; //an object of Derived type

 37:     cout << "\nFirst we use a Base pointer for access to a Base object.";
 38:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 39:     p = &baseObject;  //Point p at an object of type Base
 40:     p->setX(10);      //Use p to set the value of x in that object
 41:     cout << "\nValue of x in the Base object: " << p->getx();
 42:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 44:     cout << "\n\nNext we use the same Base pointer for access to a "
 45:         "Derived object.";
 46:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 47:     p = &derivedObject;   //Point p at an object of type Derived
 48:     p->setX(88);          //Access that Derived object


 51:     cout << "\nBut, we can't use the Base pointer p to access the "
 52:         "new data \nmember in an object of type Derived (to either "
 53:         "set or get y).";
 54:     //p->setY(88); //Compile-time error (setY not a member of Base)
 55:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 57:     cout << "\nSo we set the value of y using the object itself, rather "
 58:         "than a pointer to it.";
 59:     derivedObject.setY(99);
 60:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 62:     cout << "\nValue of x in the Derived object: " << p->getx();
 63:     cout << "\nValue of y in the Derived object: " << derivedObject.getY();
 64:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 65: }