< Previous | Contents | Next >
Introducing the Private Critter
The Private Critter program demonstrates class member access levels by declaring a class for critters that restricts direct access to an object’s data member for its hunger level. The class provides two member functions—one that allows access to the data member and one that allows changes to the data member. The program creates a new critter and indirectly accesses and changes the critter’s hunger level through these member functions. However, when the program attempts to change the critter’s hunger level to an illegal value, the member function that allows the changes catches the illegal value and doesn’t make the change. Finally, the program uses the hunger-level-setting member function with a legal value, which works like a charm. Figure 8.3 shows the results of the program.
Figure 8.3
By using a Critter object’s GetHunger() and SetHunger() member functions, the program indirectly accesses an object’s m_Hunger data member.
Setting Member Access Levels 265
You can download the code for this program from the Course Technology website (www.courseptr.com/downloads). The program is in the Chapter 8 folder; the filename is private_critter.cpp.
//Private Critter
//Demonstrates setting member access levels #include <iostream>
using namespace std;
class Critter
{
public: // begin public section Critter(int hunger = 0);
int GetHunger() const;
void SetHunger(int hunger);
private: // begin private section int m_Hunger;
};
Critter::Critter(int hunger): m_Hunger(hunger)
{
cout << "A new critter has been born!" << endl;
}
int Critter::GetHunger() const
{
return m_Hunger;
}
void Critter::SetHunger(int hunger)
{
if (hunger < 0)
{
cout << "You can’t set a critter’s hunger to a negative number.\n\n";
}
266 Chapter 8 n Classes: Critter Caretaker
else
{
m_Hunger = hunger;
}
}
int main()
{
Critter crit(5);
//cout << crit.m_Hunger; //illegal, m_Hunger is private! cout << "Calling GetHunger(): " << crit.GetHunger() << "\n\n";
cout << "Calling SetHunger() with -1.\n"; crit.SetHunger(-1);
cout << "Calling SetHunger() with 9.\n"; crit.SetHunger(9);
cout << "Calling GetHunger(): " << crit.GetHunger() << "\n\n";
return 0;
}