Source of ptr_this.cpp


  1: // Filenme: PTR_THIS.CPP
  2: // Purpose: Illustrates the implicit "this" pointer in every class.

  4: #include <iostream>
  5: using namespace std;

  7: class Time
  8: {
  9: public:
 10:     void Set(/* in */ int hours,
 11:              /* in */ int minutes,
 12:              /* in */ int seconds);

 14:     void Display() const;

 16: private:
 17:     int hours;
 18:     int minutes;
 19:     int seconds;
 20: };


 23: int main()
 24: {
 25:     cout << "\nThis program illustrates the \"this\" pointer."
 26:          << "\nThe output is irrelevant, but you should study "
 27:          << "\nthe source code carefully to see how \"this\" is used.\n";

 29:     Time t;
 30:     t.Set(11, 59, 50);
 31:     t.Display();  cout << endl;

 33:     return 0;
 34: }

 36: //******************************************************************
 37: void Time::Set(/* in */ int hours,
 38:                /* in */ int minutes,
 39:                /* in */ int seconds)
 40: {
 41:     this->hours = hours;     // Note the use of the "this" pointer.
 42:     this->minutes = minutes;
 43:     this->seconds = seconds;
 44: }

 46: //******************************************************************
 47: void Time::Display() const
 48: {
 49:     if (hours < 10)
 50:         cout << '0';
 51:     cout << hours << ':';
 52:     if (minutes < 10)
 53:         cout << '0';
 54:     cout << minutes << ':';
 55:     if (seconds < 10)
 56:         cout << '0';
 57:     cout << seconds;
 58: }