2

I have the following code:

int main() {
    int x = 3;
    int &ref = x;
    int &ref2 = ref;
    ref = 100;
    std::cout <<ref;
    std::cout <<ref2;
    return 0;
}

This print out 100 and 100. I find it confusing. My understanding was that both ref and ref2 are references to the underlying object (x=3). We then change the value of ref. As such, I expected 100 and 3.

Nick is tired
  • 6,860
  • 20
  • 39
  • 51
nz_21
  • 6,140
  • 7
  • 34
  • 80
  • 1
    `x`, `ref` and `ref2` all refer to the same `int`, why do you expect it to print who different values? – Blaze Feb 25 '20 at 11:07
  • in your code, the `x` variable will be also `100` – Raffallo Feb 25 '20 at 11:08
  • You only have one integer, `x`. You have two references to the same integer object. You cannot change the "value of `ref`", because references don't _have_ values. You can only change the value of the object it refers to, which is `x`. – Useless Feb 25 '20 at 11:08

2 Answers2

6

You don't ever change the value of ref (the language does not let you rebind a reference). In fact, this is why you need to use reference initialisation when you create a reference: you can't write int &ref; ref = x; for example.

The statement ref = 100; changes the value of the object to which the reference is bound.

Hence the output of x, ref, and ref2 are identical.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
5

My understanding was that both ref and ref2 are references to the underlying object (x=3)

Yes.

Well, they're both references to x, whose initial value is 3. Essentially you have a single integer object, which you can refer to by the names any of the names x, ref or ref2.

We then change the value of ref

No, you're contradicting yourself.

Objects have values. References like ref are not objects, but references to objects, and they don't have a value of their own to change.

You said that ref is a reference, which is true - it is a reference to an object of type int, which can take a value, and whose value is changed when you write ref = 100. The names x, ref and ref2 still refer to the same integer object afterwards, but now its value is 100 instead of 3.

You cannot reseat a reference (make it refer to a different object), and a reference does not have a value to change. It refers to an object, whose value may be changed via the reference.


NB. I don't think this question is quite a duplicate of Can we reassign the reference, even though it contains some of the same misunderstanding.

Useless
  • 64,155
  • 6
  • 88
  • 132