< Previous | Contents | Next >

Defining Accessor Member Functions

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 crits m_Hunger data member, which is 5.

268 Chapter 8 n Classes: Critter Caretaker


Tric k

image

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

image


At this point, you might be wondering why youd 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 dont generally grant full access. For example, take a look at the accessor member function I defined for setting an objects 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 its not, its 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 cant be set to a negative number. Just as Ive done here, most game programmers begin their accessor member function names with Get or Set.