home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / IDIOMS.ZIP / 5-17.C < prev    next >
C/C++ Source or Header  |  1991-12-04  |  1KB  |  57 lines

  1. /* Copyright (c) 1992 by AT&T Bell Laboratories. */
  2. /* Advanced C++ Programming Styles and Idioms */
  3. /* James O. Coplien */
  4. /* All rights reserved. */
  5.  
  6. #include <iostream.h>
  7.  
  8. class Vehicle {
  9. public:
  10.     virtual int mpg() { return 0; }
  11.     virtual void takeOff();
  12.     virtual void swim();
  13.     Vehicle(Vehicle *host) { hostVehicle = host; }
  14. private:
  15.     Vehicle *hostVehicle;
  16. };
  17.  
  18. class Plane: public Vehicle {
  19. public:
  20.     int mpg() { return 100; }
  21.     Plane(Vehicle *v) : Vehicle(v) { }
  22. };
  23.  
  24. class Boat: public Vehicle {
  25. public:
  26.     int mpg() { return 10; }
  27.     Boat(Vehicle *v) : Vehicle(v) { }
  28. };
  29.  
  30. class SeaPlane: public Vehicle {
  31. public:
  32.     SeaPlane(): Vehicle(0) {
  33.         currentMode = boat = new Boat(this);
  34.         plane = new Plane(this);
  35.     }
  36.     void takeOff() { currentMode = plane; }
  37.     void swim() { currentMode = boat; }
  38.     Vehicle *operator->() { return currentMode; }
  39. private:
  40.     Vehicle *boat, *plane, *currentMode;
  41. };
  42.  
  43. void
  44. Vehicle::takeOff() { hostVehicle->takeOff(); }
  45.  
  46. void
  47. Vehicle::swim() { hostVehicle->swim(); }
  48.  
  49. int main() {
  50.     SeaPlane seaPlane;
  51.     cout << "mpg = " << seaPlane->mpg() << endl;
  52.     seaPlane->takeOff();
  53.     cout << "mpg = " << seaPlane->mpg() << endl;
  54.     seaPlane->swim();
  55.     cout << "mpg = " << seaPlane->mpg() << endl;
  56. }
  57.