flesing
Infrastructure Builder
2
MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1
200 XP
- Time sunset(
19
,0
,0
)
;
// object of type Time
- 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:
- 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;
- }
;
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:
- int
main(
)
- {
- Time t;
- int
&
hourRef =
t.badSetHour
(
20
)
;
- cout
<<
"Hour before modification: "
<<
hourRef;
- hourRef=
30
;
// modification with invalid value
- cout
<<
"\n
Hourafter 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
;
- }
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.
Download
You must upgrade your account or reply in the thread to view the hidden content.