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
  • 3

4 Answers4

7

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
  • 119,862
  • 22
  • 374
  • 446
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
  • 245,575
  • 61
  • 446
  • 609
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
  • 90,891
  • 40
  • 158
  • 247
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
  • 79,064
  • 10
  • 147
  • 183