< Previous | Contents | Next >

Introducing the Friend Critter

Program

The Friend Critter program creates a critter object. It then uses a friend function, which is able to directly access the private data member that stores the critters name to display the critters name. Finally, the program displays the critter object by sending the object to the standard output. This is accomplished

Using Friend Functions and Operator Overloading 293


through a friend function and operator overloading. Figure 9.2 displays the results of the program.


image

Figure 9.2

The name of the critter is displayed through a friend function, and the critter object is displayed by sending it to the standard output.


You can download the code for this program from the Course Technology website (www.courseptr.com/downloads). The program is in the Chapter 9 folder; the filename is friend_critter.cpp.


//Friend Critter

//Demonstrates friend functions and operator overloading


#include <iostream> #include <string>

using namespace std; class Critter

{

//make following global functions friends of the Critter class friend void Peek(const Critter& aCritter);

friend ostream& operator<<(ostream& os, const Critter& aCritter);

294 Chapter 9 n Advanced Classes and Dynamic Memory: Game Lobby


public:

Critter(const string& name = "");


private:

string m_Name;

};


Critter::Critter(const string& name): m_Name(name)

{}


void Peek(const Critter& aCritter);

ostream& operator<<(ostream& os, const Critter& aCritter);


int main()

{

Critter crit("Poochie");


cout << "Calling Peek() to access crit’s private data member, m_Name: \n"; Peek(crit);


cout << "\nSending crit object to cout with the << operator:\n"; cout << crit;


return 0;

}


//global friend function which can access all of a Critter object’s members void Peek(const Critter& aCritter)

{

cout << aCritter.m_Name << endl;

}


//global friend function which can access all of Critter object’s members

//overloads the << operator so you can send a Critter object to cout ostream& operator<<(ostream& os, const Critter& aCritter)

{

os << "Critter Object - ";

os << "m_Name: " << aCritter.m_Name; return os;

}

Using Friend Functions and Operator Overloading 295