How To Use Reference To An Object In C++
Submitted by PhoeniciansSy on Thursday, September 25, 2014 - 10:38.
- Time sunset(19,0,0); // object of type Time
- Time &dinnerTime =sunset; // reference to a Time object
- class Time {
- public:
- // Constructor function to initialize private data.
- // Calls member function setTime to set variables.
- // Default values are 0 (see class definition).
- Time( int hr,int min, int sec )
- {
- setTime( hr, min, sec );
- }
- // Set the values of hour, minute, and second.
- void setTime( int h,int m, int s )
- {
- hour = ( h >= 0 && h < 24 ) ? h : 0;
- minute = ( m >= 0 && m < 60 ) ? m : 0;
- second = ( s >= 0 && s < 60 ) ? s : 0;
- }
- // Get the hour value
- int getHour()
- {
- return hour;
- }
- // POOR PROGRAMMING PRACTICE:
- // Returning a reference toa private data member.
- int &badSetHour( int hh) // DANGEROUS reference return
- {
- hour = ( hh >= 0 && hh < 24 ) ? hh :0;
- return hour; // DANGEROUS reference return
- }
- private:
- int hour;
- int minute;
- int second;
- };
- int main()
- {
- Time t;
- int &hourRef = t.badSetHour( 20 );
- cout << "Hour before modification: " <<hourRef;
- hourRef= 30; // modification with invalid value
- cout << "\nHourafter modification: " << t.getHour();
- // Dangerous: Function call that returns
- // a reference can be used as anlvalue!
- t.badSetHour(12) = 74;
- cout << "\n\n*********************************\n"
- << "POOR PROGRAMMING PRACTICE!!!!!!!!\n"
- << "badSetHour as an lvalue, Hour: "
- << t.getHour()
- << "\n*********************************" <<endl;
- return 0;
- }
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.
Add new comment
- 91 views