< Previous | Contents | Next >
You can define member functions outside of a class definition. Outside of the Critter class definition, I define the Critter member function Greet(), which says hi and displays the critter’s hunger level.
void Critter::Greet() // member function definition
{
cout << "Hi. I’m a critter. My hunger level is " << m_Hunger << ".\n";
}
The definition looks like any other function definition you’ve seen, except for one thing—I prefix the function name with Critter::. When you define a member function outside of its class, you need to qualify it with the class name and scope resolution operator so the compiler knows that the definition belongs to the class.
In the member function, I send m_Hunger to cout. This means that Greet() displays the value of m_Hunger for the specific object through which the function is called. This simply means that the member function displays the critter’s hunger level. You can access the data members and member functions of an object in any member function simply by using the member’s name.