< Previous | Contents | Next >
An accessor member function allows indirect access to a data member. Because m_Hunger is private, I wrote an accessor member function, GetHunger(), to return the value of the data member. (For now, you can ignore the keyword const.)
int Critter::GetHunger() const
{
return m_Hunger;
}
I put the member function to work in main() with the following line:
cout << "Calling GetHunger(): " << crit.GetHunger() << "\n\n";
In the preceding code, crit.GetHunger() simply returns the value of crit’s m_Hunger data member, which is 5.
268 Chapter 8 n Classes: Critter Caretaker
Tric k
Just as you can with regular functions, you can inline member functions. One way to inline a member function is to define it right inside of the class definition, where you’d normally only declare the member function. If you include a member function definition in a class, then of course you don’t need to define it outside of the class.
An exception to this rule is that when you define a member function in a class definition using the keyword virtual, the member function is not automatically inlined. You’ll learn about virtual functions in Chapter 10, “Inheritance and Polymorphism: Blackjack.”
At this point, you might be wondering why you’d go to the trouble of making a data member private only to grant full access to it through accessor functions. The answer is that you don’t generally grant full access. For example, take a look at the accessor member function I defined for setting an object’s m_Hunger data member, SetHunger():
void Critter::SetHunger(int hunger)
{
if (hunger < 0)
{
cout << "You can’t set a critter’s hunger to a negative number.\n\n";
}
else
{
m_Hunger = hunger;
}
}
In this accessor member function, I first check to make sure that the value passed to the member function is greater than zero. If it’s not, it’s an illegal value and I display a message, leaving the data member unchanged. If the value is greater than zero, then I make the change. This way, SetHunger() protects the integrity of m_Hunger, ensuring that it can’t be set to a negative number. Just as I’ve done here, most game programmers begin their accessor member function names with Get or Set.