< Previous | Contents | Next >

Specifying Public and Private Access

Levels

Every class data member and member function has an access level, which determines from where in your program you can access it. So far, Ive 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:, Im 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:, Im 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 objects m_Hunger data member. Therefore, I cant directly access an objects m_Hunger data member through the object in main() as Ive 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 cant access it from code that is not part of the Critter class. Again, only code thats part of Critter can directly access the data member.

Ive 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.