nz_21
nz_21

Reputation: 7343

understanding references in c++

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.

Upvotes: 2

Views: 215

Answers (2)

Bathsheba
Bathsheba

Reputation: 234635

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.

Upvotes: 6

Useless
Useless

Reputation: 67713

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.

Upvotes: 5

Related Questions