Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++: Why I can change the assignment of reference on my computer?

I am new to C++, and I am studying the concept of reference.

I have studied the fact that a reference should not be assigned to something else once defined and initialized, the description of reference on C++ primer states that once you have bound a reference to an object, then you can’t change the object which the reference is bounded to.

I am confused by this statement. I tried the following code on my computer, the compiler didn’t report neither warnings nor errors.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

int a = 2;
int b = 4;
int &ref = a;
cout << "ref = " << ref << endl;
ref = b;
cout << "ref = " << ref << endl;

On my computer, the compilation passes, and outputs were printed, one is 2, the other is 4, there’s no problem at all.

I am confused by this concept of reference, is it the condition that we SHOULD NOT change the object which the reference is bounded to, or we CANNOT change the object which the reference is bounded to?

P.S. Even the page 58 on C++ primer also demonstrates the example where the reference refers to new object, and the book says it’s ok to do that. Like this:

int i = 42;
int *p;
int *&r = p;
r = &i; // isn't this changing r to an new object?
*r = 0;

>Solution :

then you can’t change the object which the reference is bounded to.

I am confused by this statement

The statement tries to say, that the reference cannot be modified to refer to another object. The object that is referred can be modified.

When left hand operand of assignment is a reference, you are indirecting through the reference, and assigning the value of the referred object.

ref = b;

ref still refers to the object named by a. That object is modified by this assignment. After the assignment, the value of a is 4.

r = &i; // isn't this changing r to an new object?

r still refers to the object named by p. That object is modified by this assignment. After the assignment, p points to i.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading