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.