< Previous | Contents | Next >

Creating Friend Functions

A friend function can access any member of a class of which its a friend. You specify that a function is a friend of a class by listing the function prototype preceded by the keyword friend inside the class definition. Thats what I do inside the Critter definition with the following line, which says that the global function Peek() is a friend of Critter.

friend void Peek(const Critter& aCritter);

This means Peek() can access any member of Critter even though its not a member function of the class. Peek() takes advantage of this relationship by accessing the private data member m_Name to display the name of a critter passed to the function.

void Peek(const Critter& aCritter)

{

cout << aCritter.m_Name << endl;

}

When I call Peek() in main() with the following line, the private data member

m_Name of crit is displayed and Poochie appears on the screen.

Peek(crit);