< Previous | Contents | Next >

Altering an Object through a Returned Reference

You can also alter the object to which a returned reference refers. This means you can change the heros inventory through rStr, as in the following line of code.

rStr = "Healing Potion";

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

cout << inventory[1] << endl;

If I want to protect inventory so a reference returned by refToElement() cant be used to change the vector, I should specify the return type of the function as a constant reference.

Introducing the Tic-Tac-Toe Game 203