Click to See Complete Forum and Search --> : returning a reference to a private data


joeycbulk
February 1st, 2007, 12:28 PM
Hi! I'm reading this book from deitel & deitel and a part of this code I cant understand.

1: class Time {
2: public:
3: Time( int = 0, int = 0, int = 0 );
4: void setTime( int, int, int );
5: int getHour();
6: int &badSetHour( int );
7:private:
8: int hour;
9: int minute;
10: int second;
11: };

12: Time::Time( int hr, int min, int sec ) { setTime( hr, min, sec ); }

13: void Time::setTime( int h, int m, int s )
14: {
15: hour = ( h >= 0 && h < 24 ) ? h : 0;
16: minute = ( m >= 0 && m < 60 ) ? m : 0;
17: second = ( s >= 0 && s < 60 ) ? s : 0;
18: }

19: int Time::getHour() { return hour; }

20: int &Time::badSetHour( int hh )
21: {
22: hour = ( hh >= 0 && hh < 24 ) ? hh : 0;
23: return hour;
24: }

25: int main()
26: {
27: Time t;
28: t.badSetHour(12) = 74; //<<<<<<<<<<<
30: cout << t.getHour() << endl;
31: return 0;
32: }

At line 28 I was able to use t.badSetHour as an lvalue.

I dont know why the code was able to use it as an lvalue. Could some pls help me understand why... Thanks!

The book just told me not to use this reference return because I was able to assign an invalid value of 74.

Zaccheus
February 1st, 2007, 03:16 PM
20: int &Time::badSetHour( int hh )
21: {
22: hour = ( hh >= 0 && hh < 24 ) ? hh : 0;
23: return hour;
24: }
hour was declared private so that code outside the class cannot access it directly. You can only set the hour value by calling a function which first checks whether the new value is valid (i.e. >= 0 and < 24).

But the & between int and Time:: means that the function is returning a reference to the data member 'hour', and if you have a reference to a data member then you can assign values to the data member directly without calling badSetHour.

joeycbulk
February 1st, 2007, 10:37 PM
20: int &Time::badSetHour( int hh )
21: {
22: hour = ( hh >= 0 && hh < 24 ) ? hh : 0;
23: return hour;
24: }
hour was declared private so that code outside the class cannot access it directly. You can only set the hour value by calling a function which first checks whether the new value is valid (i.e. >= 0 and < 24).

But the & between int and Time:: means that the function is returning a reference to the data member 'hour', and if you have a reference to a data member then you can assign values to the data member directly without calling badSetHour.

thanks! Now I know that its because of the return hour;.