How To Use Reference To An Object In C++

  1. Time sunset(19,0,0); // object of type Time
  2. Time &dinnerTime =sunset;  // reference to a Time object
Defining a reference to an object is equal to defining an alias to this object. We can use the reference in the left side of an assignment, that means we can assign a new value to this reference and change the original object that is referenced. We can write a public member function in a class that returns a reference to private data member, let us have the following class:
  1. class Time {
  2.    public:
  3.       // Constructor function to initialize private data.
  4.       // Calls member function setTime to set variables.
  5.       // Default values are 0 (see class definition).
  6.       Time( int hr,int min, int sec )
  7.       {
  8.          setTime( hr, min, sec );
  9.       }
  10.       // Set the values of hour, minute, and second.
  11.       void setTime( int h,int m, int s )
  12.       {
  13.          hour = ( h >= 0 && h < 24 ) ? h : 0;
  14.          minute = ( m >= 0 && m < 60 ) ? m : 0;
  15.          second = ( s >= 0 && s < 60 ) ? s : 0;
  16.       }
  17.       // Get the hour value
  18.       int getHour()
  19.       {
  20.          return hour;
  21.       }
  22.       // POOR PROGRAMMING PRACTICE:
  23.       // Returning a reference toa private data member.
  24.       int &badSetHour( int hh) // DANGEROUS reference return
  25.       {
  26.          hour = ( hh >= 0 && hh < 24 ) ? hh :0;
  27.          return hour;  // DANGEROUS reference return
  28.       }
  29.    private:
  30.       int hour;
  31.       int minute;
  32.       int second;
  33. };
You can notice that badSetHour() member function returns a reference to 'hour' data member, so any change has been made on this reference will change the value of 'hour' data member like in the following example:
  1. int main()
  2. {
  3.    Time t;
  4.    int &hourRef = t.badSetHour( 20 );
  5.  
  6.    cout << "Hour before modification: " <<hourRef;
  7.    hourRef= 30;  // modification with invalid value
  8.    cout << "\nHourafter modification: " << t.getHour();
  9.  
  10.    // Dangerous: Function call that returns
  11.    // a reference can be used as anlvalue!
  12.    t.badSetHour(12) = 74;
  13.    cout << "\n\n*********************************\n"
  14.    << "POOR PROGRAMMING PRACTICE!!!!!!!!\n"
  15.    << "badSetHour as an lvalue, Hour: "
  16.    << t.getHour()
  17.    << "\n*********************************" <<endl;
  18.  
  19.    return 0;
  20. }
The output:
Hour before modification: 20 Hour after modification: 30 ********************************* POOR PROGRAMMING PRACTICE!!!!!!!! badSetHour as an lvalue, Hour: 74 *********************************
Note: You can find the full source code of this example in code.zip file.
Tags

Add new comment