Tue Dec 22 11:08:16 1992 shape2.tmp Page 1, Line 1 1 /* 2 * shape2.cpp -- example of public inheritance. 3 */ 4 5 #include 6 7 class Point // a Point (location) 8 { 9 public: 10 typedef float Coord; // Coord type 11 12 Point (Coord x, Coord y) { xpos = x; ypos = y; } 13 void move (Coord dx, Coord dy) { xpos += dx; ypos += dy; } 14 15 Coord xpos, ypos; // a Point HAS x and y coordinated 16 }; 17 18 class Shape // an undefined shape 19 { 20 public: 21 typedef float Angle; // Angle type 22 typedef float Length; // Length type 23 24 Shape (Coord x = 0, Coord y = 0, Angle a = 0) : center(x, y), angle(a) { } 25 26 virtual void draw () const = 0; // pure virtual function 27 void move (Coord dx, Coord dy) { center.move (dx, dy); } 28 void rotate (Angle a) { angle += a; } 29 30 protected: 31 Angle angle; // a Shape HAS A angle 32 Point center; // a Shape HAS A center location 33 }; 34 35 class Circle : public Shape // a Circle IS A Shape 36 { 37 public: 38 Circle (Length r = 0) : radius(r) { } // empty 39 40 void draw () const; 41 42 private: 43 Length radius; // a Circle HAS A radius 44 }; 45 46 void Circle::draw() const // Circle draw member function 47 { 48 printf("Circle::draw(): <%g, %g, %g>\n", center.xpos, center.ypos, radius); 49 } 50 51 class Rectangle : public Shape // a Rectangle IS A Shape 52 { 53 public: 54 Rectangle (Length w = 0, Length h = 0, 55 Coord x = 0, Coord y = 0, Angle a = 0 ) 56 : Shape(x, y, a), width(w), height(h) { } 57 58 void draw() const; 59 60 private: 61 Length width, height; // a Rectangle HAS witdh and height 62 }; 63 64 void Rectangle::draw() const // Rectangle draw member function 65 { 66 printf("Rectangle::draw(): <%g, %g, %g, %g, %g>\n", 67 center.xpos, center.ypos, width, height, angle); 68 } 69 70 void main() 71 { 72 // Shape s; // we don't want to be able to create a Shape 73 Circle c(1); 74 Rectangle r(2, 3); 75 76 // draw shapes move shapes draw shapes 77 c.draw (); c.move ( 10, -20); c.draw (); 78 r.draw (); r.move (-30, 40); r.draw (); 79 80 // draw shapes via pointer to shape 81 // Shape *ssp = &s; ssp->draw (); // a Shape 82 Shape *scp = &c; scp->draw (); // a Circle ISA Shape 83 Shape *srp = &r; srp->draw (); // a Rectangle ISA Shape 84 } 85 86 /*** End of file ***/ Program output: Circle::draw(): <0, 0, 1> Circle::draw(): <10, -20, 1> Rectangle::draw(): <0, 0, 2, 3, 0> Rectangle::draw(): <-30, 40, 2, 3, 0> Circle::draw(): <10, -20, 1> Rectangle::draw(): <-30, 40, 2, 3, 0>