Source of inherit5.cpp


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

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

  6: class ShapeWithArea
  7: {
  8: public:
  9:     void setDimensions
 10:     (
 11:         double dim1, //in
 12:         double dim2  //in
 13:     )
 14:     {
 15:         dimension1 = dim1;
 16:         dimension2 = dim2;
 17:     }

 19:     void getDimensions
 20:     (
 21:         double &dim1, //out
 22:         double &dim2  //out
 23:     )
 24:     {
 25:         dim1 = dimension1;
 26:         dim2 = dimension2;
 27:     }

 29:     virtual double getArea()
 30:     { 
 31:         cout << "\nThis is the getArea() function of the ShapeWithArea "
 32:             "base class.\nYou must override this function, or your area "
 33:             "will always be 0.";
 34:         cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 35:         return 0.0;
 36:     }

 38: private:
 39:     //Dimensions of figure
 40:     double dimension1;
 41:     double dimension2;
 42: };

 44: class Rectangle : public ShapeWithArea
 45: {
 46: public:
 47:     double getArea() 
 48:     {
 49:         double dim1, dim2;
 50:         getDimensions(dim1, dim2);
 51:         return dim1 * dim2;
 52:     }
 53: };

 55: class Triangle : public ShapeWithArea
 56: {
 57: public:
 58:     double getArea()
 59:     {
 60:         double dim1, dim2;
 61:         getDimensions(dim1, dim2);
 62:         return 0.5 * dim1 * dim2;
 63:     }
 64: };


 67: int main()
 68: {
 69:     cout << "\nThis program illustrates the use of a virtual function to "
 70:         "help define an\n\"interface\". The user is asked to override the "
 71:         "base class virtual function\nin any class derived from this base "
 72:         "class.";
 73:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 75:     ShapeWithArea a;

 77:     cout << "\nArea of any ShapeWithArea object: " << a.getArea();
 78:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 80:     ShapeWithArea *p;

 82:     cout << "\nNow we create a 3 by 4 rectangle.";
 83:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 84:     Rectangle r;
 85:     r.setDimensions(3.0, 4.0);
 86:     p = &r;
 87:     cout << "\nArea of this rectangle: " << p->getArea();
 88:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 90:     cout << "\nNext we create a triangle with base 4 and height 5.";
 91:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 92:     Triangle t;
 93:     t.setDimensions(4.0, 5.0);
 94:     p = &t;
 95:     cout << "\nArea of this triangle: " << p->getArea();
 96:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 97: }