2

I've read that once a reference is initialized to an object, it cannot be changed. The following code works, so perhaps I am misunderstanding the concept? (Or do they mean this more in an immutable sense?)

int main()
{

    int x = 4;
    int& j = x;
    cout << j << endl;
    int y = 5;
    j = y;
    cout << j << endl;
}
VeritasK
  • 65
  • 4

4 Answers4

8

The following code works, so perhaps I am misunderstanding the concept?

Indeed I'm afraid you are misunderstanding the concept. The expression:

j = y;

Does not re-bind j so that it becomes a reference to y: rather, it assigns the value of y to the object referenced by j. Try this after the assignment:

cout << (&j == &x)

And you will see that 1 is printed (meaning j is still an alias for x).

After initialization, a reference becomes an alias for the object it is bound to. Everything you do on the reference, you do it on the object being referenced.

A reference cannot be re-bound or unbound, and it practically becomes just an alternative name for the object it is bound to.

Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
3

You're just assigning to the reference, not binding it to a new "object" (technically, not an object). If you print out x, you'll see that it too has changed (omg) :)

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
3

What was being conveyed is that a reference cannot be rebound. The assignment is affecting x, not j. The variable j on the other hand is still bound to x even after the assignment.

David G
  • 94,763
  • 41
  • 167
  • 253
2

The reference can't be made to point to a different object at a different Address, but as here, the value of the object itself can be changed.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186