< Previous | Contents | Next >

Defining Member Functions

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 critters hunger level.

Defining New Types 259



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 youve seen, except for one thingI 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 critters hunger level. You can access the data members and member functions of an object in any member function simply by using the members name.