< Previous | Contents | Next >

Creating References

The first thing I do in main() is create a variable to hold my score.

int myScore = 1000;

Then I create a reference that refers to myScore.

int& mikesScore = myScore; //create a reference

The preceding line declares and initializes mikesScore, a reference that refers to myScore. mikesScore is an alias for myScore. mikesScore does not hold its own int value; its simply another way to get at the int value that myScore holds.

To declare and initialize a reference, start with the type of value to which the reference will refer, followed by the reference operator (&), followed by the reference name, followed by =, followed by the variable to which the reference will refer.


Tric k

image

Sometimes programmers prefix a reference name with the letter “r” to remind them that they’re working with a reference. A programmer might include the following lines:

int playerScore = 1000; int& rScore = playerScore;

image


One way to understand references is to think of them as nicknames. For example, suppose youve got a friend named Eugene, and he (understandably) asks to be called by a nicknameGibby (not much of an improvement, but its what Eugene

190 Chapter 6 n References: Tic-Tac-Toe


wants). So when youre at a party with your friend, you can call him over using either Eugene or Gibby. Your friend is only one person, but you can call him using either his name or a nickname. This is the same way a variable and a reference to that variable work. You can get to a single value stored in a variable by using its variable name or the name of a reference to that variable. Finally, whatever you do, try not to name your variables Eugenefor their sakes.


Tra p

image

Because a reference must always refer to another value, you must initialize the reference when you declare it. If you don’t, you’ll get a compile error. The following line is quite illegal:

int& mikesScore; //don’t try this at home!

image