Sams Teach Yourself C in 21 Days

(singke) #1
Working with C++ Classes and Objects 679

BD3


75: minutes -= 60;
76: }
77: }
78:
79: // Add 1 to the number of seconds
80: //--------------------------------
81: void time::add_second(void)
82: {
83: seconds += 1;
84: while (seconds >= 60)
85: {
86: add_minute();
87: seconds -= 60;
88: }
89: }
90:
91: // Initialize data member values
92: //-------------------------------
93: void time::init(int h, int m, int s)
94: {
95: hours = h;
96: minutes = m;
97: seconds = s;
98: }

Start time: 7:15:20
End time: 10:20:30

Start time: 7:15:20
New end time: 11:21:31
You can see that the access to the members of the timeclass is being controlled
in this listing. In line 6, the privatekeyword is being used to explicitly create
private values. In this listing, the data members—hours, minutes, and seconds—are all
private. This means that only the member functions of the timeclass can access these
private data members. The publickeyword is being used in line 12 to declare public val-
ues. The member functions init(),display_time(), and the add...functions are all
public.
You should notice that a new member function has been included in line 14 of the time
class. This function, called init(), is included in order to set the initial values of the pri-
vate data members. Because the data members are declared as private, you can only
access them by using a member function within the class. You cannot set the values from
themain()function of this listing, as you did in Listing B3.3.

LISTINGB3.4 continued

OUTPUT

ANALYSIS

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

Free download pdf