... minute and/or second was out of range");
18      }
19    }
20
21    // return hour value
22    unsigned int Time::getHour() const {return hour;}
23
24    // poor practice: returning a reference to a private data member.
25    unsigned int& Time::badSetHour(int hh) {                         
26       if (hh >= 0 && hh < 24) {
27          hour = hh;
28       }
29       else {
30          throw invalid_argument("hour must be 0-23");
31       }
32
33       return hour; // dangerous reference return
34    }

Figure 9.13 declares Time object t (line 9) and reference hourRef (line 12), which is initialized with the reference returned by the call t.badSetHour(20). Line 14 displays the value of the alias hourRef. This shows how hourRef breaks the encapsulation of the class—statements in main should not have access to the private data in an object ...

Get C++ How to Program, 10/e now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.