Sams Teach Yourself C in 21 Days

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

BD3


Declaring Protected Data
The third access modifier is protected. Protected data members are treated differently
than public and private ones. The protectedkeyword will be covered in more detail
later today after you learn about inheritance.

Setting the Access Type on Class Data ........................................................


You now know that structures have public data by default and that normal classes have
private members by default. What do you do if you want to change these access modes?
This is simple. You use the public,private, andprotectedkeywords in your pro-
grams’ classes. Listing B3.4 rewrites Listing B3.3 explicitly using the publicandpri-
vatekeywords.

LISTINGB3.4 access.cpp. Declaring, defining, and using private and public data
1: // Controlling data access to data members and member functions
2: #include <iostream.h>
3:
4: class time {
5:
6: private:
7: // Data Members:
8: int hours;
9: int minutes;
10: int seconds;
11:
12: public:
13: // Member Functions:
14: void init( int h, int m, int s);
15: void print_time(void);
16: void add_hour(void);
17: void add_minute(void);
18: void add_second(void);
19: };
20:
21: int main(int argc, char* argv[])
22: {
23: time start_time;
24: time end_time;
25:

Whenever possible, you should declare the data members of your class as
Tip private instead of public. You can use member functions to access data.

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

Free download pdf