< Previous | Contents | Next >

Altering an Object through a Returned Pointer

You can also alter the object to which a returned pointer points. This means that I can change the heros inventory through pStr.

*pStr = "Healing Potion";

Because pStr points to the element in position 1 of inventory, this code changes inventory[1] so its equal to "Healing Potion". To prove this, I display the element with the following line, which does indeed show Healing Potion.

cout << inventory[1] << endl;

For an abstract representation, check out Figure 7.7, which shows the status of the variables after the assignment.


Hin t

image

If you want to protect an object pointed to by a returned pointer, make sure to restrict the pointer. Return either a pointer to a constant or a constant pointer to a constant.

image

244 Chapter 7 n Pointers: Tic-Tac-Toe 2.0



image

Figure 7.7

inventory[1] is changed through the returned pointer stored in pStr.