home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C15 / Wind4.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.9 KB  |  96 lines

  1. //: C15:Wind4.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Extensibility in OOP
  7. #include <iostream>
  8. using namespace std;
  9. enum note { middleC, Csharp, Cflat }; // Etc.
  10.  
  11. class Instrument {
  12. public:
  13.   virtual void play(note) const {
  14.     cout << "Instrument::play" << endl;
  15.   }
  16.   virtual char* what() const {
  17.     return "Instrument";
  18.   }
  19.   // Assume this will modify the object:
  20.   virtual void adjust(int) {}
  21. };
  22.  
  23. class Wind : public Instrument {
  24. public:
  25.   void play(note) const {
  26.     cout << "Wind::play" << endl;
  27.   }
  28.   char* what() const { return "Wind"; }
  29.   void adjust(int) {}
  30. };
  31.  
  32. class Percussion : public Instrument {
  33. public:
  34.   void play(note) const {
  35.     cout << "Percussion::play" << endl;
  36.   }
  37.   char* what() const { return "Percussion"; }
  38.   void adjust(int) {}
  39. };
  40.  
  41. class Stringed : public Instrument {
  42. public:
  43.   void play(note) const {
  44.     cout << "Stringed::play" << endl;
  45.   }
  46.   char* what() const { return "Stringed"; }
  47.   void adjust(int) {}
  48. };
  49.  
  50. class Brass : public Wind {
  51. public:
  52.   void play(note) const {
  53.     cout << "Brass::play" << endl;
  54.   }
  55.   char* what() const { return "Brass"; }
  56. };
  57.  
  58. class Woodwind : public Wind {
  59. public:
  60.   void play(note) const {
  61.     cout << "Woodwind::play" << endl;
  62.   }
  63.   char* what() const { return "Woodwind"; }
  64. };
  65.  
  66. // Identical function from before:
  67. void tune(Instrument& i) {
  68.   // ...
  69.   i.play(middleC);
  70. }
  71.  
  72. // New function:
  73. void f(Instrument& i) { i.adjust(1); }
  74.  
  75. // Upcasting during array initialization:
  76. Instrument* A[] = {
  77.   new Wind,
  78.   new Percussion,
  79.   new Stringed,
  80.   new Brass,
  81. };
  82.  
  83. int main() {
  84.   Wind flute;
  85.   Percussion drum;
  86.   Stringed violin;
  87.   Brass flugelhorn;
  88.   Woodwind recorder;
  89.   tune(flute);
  90.   tune(drum);
  91.   tune(violin);
  92.   tune(flugelhorn);
  93.   tune(recorder);
  94.   f(flugelhorn);
  95. } ///:~
  96.