Sams Teach Yourself C in 21 Days

(singke) #1
67: int time::get_hours()
68: {
69: return hours;
70: }
71: int time::get_minutes()
72: {
73: return minutes;
74: }
75: int time::get_seconds()
76: {
77: return seconds;
78: }
79: void time::set_hours( int h )
80: {
81: hours = h;
82: }
83: void time::set_minutes( int m )
84: {
85: minutes = m;
86: }
87: void time::set_seconds( int s )
88: {
89: seconds = s;
90: }

My time is: 11:43:20
Resetting time to 3:12:30...
The hours are now: 3
The minutes are now: 12
The seconds are now: 30Press
This listing has cut out some of the member functions from the timeclass. Six
new member functions have been added. Within the class, you can see that the
first three in lines 15–17 each set a data member’s value. In lines 19–21 the second three
are presented. Each of these returns a value from one of the data members. The defini-
tions for these functions are in lines 67–90.
So why would you create the private data members and use access member functions if
doing so adds so much more code? It seems like simply making the data all public would
be the easiest solution.
Although adding member functions seems like a lot of additional work, it actually
enables you to encapsulate your program’s functionality. It also gives you the capability
to make changes to the class’s data members without having to change all of the pro-
grams that use your class. Consider an example of how using access functions can help

682 Bonus Day 3

LISTINGB3.5 continued

OUTPUT

ANALYSIS

38 448201x-Bonus3 8/13/02 11:19 AM Page 682

Free download pdf