Sams Teach Yourself C in 21 Days

(singke) #1
Theinit()function is called in lines 26 and 27. As you can see, this function sets the
values of the data members in the timeclass. Looking at the function definition in lines
91–98, you see that the function simply sets the hours, minutes, and seconds values in
the class to those passed to the initialization function.
To fully understand the access keywords, add the following between lines 27 and 29:
time.hour = 5;
When you execute the listing with this line, you’ll get an error. The reason for the error
is because houris a private member of the timeclass, and private members can only be
accessed from member functions within the class.

Creating Access Member Functions ..................................................................


If you set up your member data variables to be private, how do you access them? Listing
B3.4 doesn’t have an easy way to get the value of hours, minutes, or seconds. How
should you set these values individually, and how would you access them? The title of
this section gives away the answer to this question. To access the data, you simply set up
access member functions.
An access member function is a public member function with the sole purpose of setting
or getting a data member within the class. Generally, these functions will be a few lines
in length. Listing B3.5 presents the timestructure with access functions added. To cut
down the size of the listing, the add...functions have been removed.

LISTINGB3.5 property.cpp. Using access member functions
1: // Using access functions
2: #include <iostream.h>
3:
4: class time {
5:
6: private:
7: int hours;
8: int minutes;
9: int seconds;
10:
11: public:
12: void init( int h, int m, int s);
13: void print_time(void);
14:
15: void set_hours( int h);
16: void set_minutes( int m );
17: void set_seconds( int s );

680 Bonus Day 3

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

Free download pdf