home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C10 / Selfmem.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  661 b   |  28 lines

  1. //: C10:Selfmem.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. // Static member of same type
  7. // ensures only one object of this type exists.
  8. // Also referred to as a "singleton" pattern.
  9. #include <iostream>
  10. using namespace std;
  11.  
  12. class Egg {
  13.   static Egg e;
  14.   int i;
  15.   Egg(int ii) : i(ii) {}
  16. public:
  17.   static Egg* instance() { return &e; }
  18.   int val() { return i; }
  19. };
  20.  
  21. Egg Egg::e(47);
  22.  
  23. int main() {
  24. //!  Egg x(1); // Error -- can't create an Egg
  25.   // You can access the single instance:
  26.   cout << Egg::instance()->val() << endl;
  27. } ///:~
  28.