home *** CD-ROM | disk | FTP | other *** search
/ CD Actual 13 / CDA13.ISO / cdactual / demobin / share / program / C / ANSICPP.ZIP / EX07019.CPP < prev    next >
Encoding:
C/C++ Source or Header  |  1990-07-24  |  1.5 KB  |  79 lines

  1. // ex07019.cpp
  2. // The this pointer
  3. #include <iostream.h>
  4. #include <string.h>
  5.  
  6. // ------- date class
  7. class Date {
  8.     int mo, da, yr;
  9.     char *month;
  10. public:
  11.     Date();
  12.     Date(int m, int d, int y);
  13.     ~Date();
  14.     Date& operator=(Date&); //overloaded assignment operator
  15.     void display();
  16. };
  17. // constructor that is called for an uninitialized Date
  18. Date::Date()
  19. {
  20.     mo = 0; da = 0; yr = 0;
  21.     month = NULL;    
  22. }
  23. // constructor that is called for an initialized Date
  24. Date::Date(int m, int d, int y)
  25. {
  26.     static char *mos[] = {
  27.         "January", "February", "March", "April", "May", 
  28.         "June",    "July", "August", "September", "October", 
  29.         "November",    "December"
  30.     };
  31.     mo = m; da = d; yr = y;
  32.     month = new char[strlen(mos[m-1])+1];
  33.     strcpy(month, mos[m-1]);
  34. }
  35.  
  36. // Destructor for a Date
  37. Date::~Date()
  38. {
  39.     if (month != NULL)
  40.         delete month;
  41. }
  42.  
  43. // ----------- display member function
  44. void Date::display() 
  45. {
  46.     if (month != NULL)
  47.         cout << '\n' << month << ' ' << da << ", " 
  48.              << yr+1900;
  49. }
  50.  
  51. // ---------- overloaded Date assignment
  52. Date& Date::operator=(Date& dt)
  53. {
  54.     mo = dt.mo;
  55.     da = dt.da;
  56.     yr = dt.yr;
  57.     if (month != NULL)
  58.         delete month;
  59.     if (dt.month != NULL)    {
  60.         month = new char [strlen(dt.month)+1];
  61.         strcpy(month, dt.month);
  62.     }
  63.     else
  64.         month = NULL;
  65.     return *this;
  66. }
  67.  
  68. main()
  69. {
  70.     // ------ original date
  71.     Date birthday(6,24,40);
  72.     Date oldday, newday;
  73.     // ------ assign first to second to third
  74.     oldday = newday = birthday;
  75.     birthday.display();
  76.     oldday.display();
  77.     newday.display();
  78. }
  79.