c++ – Change the object pointed to by the link


Scott Meyers says:

If so, it undermines the basics, because C ++ does not allow you to change the referenced object .

Question: Why does the below code work in VS2017?

int main()
    int i = 10;
    int& r = i;


    int j = 20;
    r = j;

    i = 5;

    int& r2 = r;

    return 0;


Apparently, you came across this text here . But there we are talking about something completely different – the assignment of two variables, which are class objects in which there is a reference member.

And the question of what should happen with the link. The context does not mean that you cannot change the object itself through a link, but that the link cannot suddenly start pointing to another object along the way.

C ++ does not allow you to change the value of the reference itself, and not the object it points to, in any way. A reference, unlike a pointer, cannot first point to object a , and then suddenly to object b . Only to one and the same object – the one with which it is initialized – all the time of its existence.

Is that clearer?

Yes, the phrase is translated somewhat ambiguously, I admit it …

Scroll to Top