< Previous | Contents | Next >
Specifying Public and Private Access
Every class data member and member function has an access level, which determines from where in your program you can access it. So far, I’ve always specified class members to have public access levels using the keyword public. Again in Critter, I start a public section with the following line:
public: // begin public section
By using public:, I’m saying that any data member or member function that follows (until another access level specifier) will be public. This means that any part of the program can access them. Because I declare all of the member functions in this section, it means that any part of my code can call any member function through a Critter object.
Next, I specify a private section with the following line:
private: // begin private section
Setting Member Access Levels 267
By using private:, I’m saying that any data member or member function that follows (until another access level specifier) will be private. This means that only code in the Critter class can directly access it. Since I declare m_Hunger in this section, it means that only the code in Critter can directly access an object’s m_Hunger data member. Therefore, I can’t directly access an object’s m_Hunger data member through the object in main() as I’ve done in previous programs. So the following line in main(), if uncommented, would be an illegal statement:
//cout << crit.m_Hunger; //illegal, m_Hunger is private!
Because m_Hunger is private, I can’t access it from code that is not part of the Critter class. Again, only code that’s part of Critter can directly access the data member.
I’ve only shown you how to make data members private, but you can make member functions private, too. Also, you can repeat access modifiers. So if you want, you could have a private section, followed by a public section, followed by another private section in a class. Finally, member access is private by default. Until you specify an access modifier, any class members you declare will be private.