3.4 Can I redirect a reference later on?

Now that we see the usefulness of a reference, the question is whether we can change a reference so it becomes an alias of some other objects after its initialization.

In other words, we want to do this:

int i;
int k;
int &j = i;

// j is an alias of i
j = k;
// is j an alias of k now?

In this code, the assignment operation j = k means the following: ``evaluate the expression k, then store the value in whatever j refers to''. This is the same as i = k because j is a reference to i. Hmmm, we did not change j to refer to another object.

The assignment j = &k; fails to compile because j is a reference to an integer, but &k is the address (a pointer) of k. A reference is not a pointer!

There is no way to alter a reference after it is initialized.



Copyright © 2006-09-19 by Tak Auyeung