< Previous | Contents | Next >

Overloading Operators

Overloading operators might sound like something you want to avoid at all costsas in, Look out, that operator is overloaded and shes about to blow!”— but its not. Operator overloading lets you give meaning to built-in operators used with new types that you define. For example, you could overload the * operator so that when it is used with two 3D matrices (objects instantiated from some class that youve defined), the result is the multiplication of the matrices.

To overload an operator, define a function called operatorX, where X is the operator you want to overload. Thats what I do when I overload the << operator; I define a function named operator<<.

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

{

os << "Critter Object - ";

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

}

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


The function overloads the << operator so that when I send a Critter object with the << to cout, the data member m_Name is displayed. Essentially, the function allows me to easily display Critter objects. The function can directly access the private data member m_Name of a Critter object because I made the function a friend of the Critter class with the following line in Critter:

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

This means I can simply display a Critter object by sending it to cout with the

<< operator, which is what I do in main() with the following line, which displays the text Critter Object – m_Name: Poochie.

cout << crit;


Hi n t

image

With all the tools and debugging options available to game programmers, sometimes simply displaying the values of variables is the best way to understand what’s happening in your programs. Overloading the << operator can help you do that.

image


This function works because cout is of the type ostream, which already overloads the << operator so that you can send built-in types to cout.