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

  1. //: C11:HowMany2.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. // The copy-constructor
  7. #include <fstream>
  8. #include <cstring>
  9. using namespace std;
  10. ofstream out("HowMany2.out");
  11.  
  12. class HowMany2 {
  13.   static const int bufsize = 30;
  14.   char name[bufsize]; // Object identifier
  15.   static int object_count;
  16. public:
  17.   HowMany2(const char* id = 0) {
  18.     if(id) strncpy(name, id, bufsize);
  19.     else *name = 0;
  20.     ++object_count;
  21.     print("HowMany2()");
  22.   }
  23.   // The copy-constructor:
  24.   HowMany2(const HowMany2& h) {
  25.     strncpy(name, h.name, bufsize);
  26.     strncat(name, " copy", bufsize - strlen(name));
  27.     ++object_count;
  28.     print("HowMany2(HowMany2&)");
  29.   }
  30.   // Can't be static (printing name):
  31.   void print(const char* msg = 0) const {
  32.     if(msg) out << msg << endl;
  33.     out << '\t' << name << ": "
  34.         << "object_count = "
  35.         << object_count << endl;
  36.   }
  37.   ~HowMany2() {
  38.     --object_count;
  39.     print("~HowMany2()");
  40.   }
  41. };
  42.  
  43. int HowMany2::object_count = 0;
  44.  
  45. // Pass and return BY VALUE:
  46. HowMany2 f(HowMany2 x) {
  47.   x.print("x argument inside f()");
  48.   out << "returning from f()" << endl;
  49.   return x;
  50. }
  51.  
  52. int main() {
  53.   HowMany2 h("h");
  54.   out << "entering f()" << endl;
  55.   HowMany2 h2 = f(h);
  56.   h2.print("h2 after call to f()");
  57.   out << "call f(), no return value" << endl;
  58.   f(h);
  59.   out << "after call to f()" << endl;
  60. } ///:~
  61.