Iv got to the stage in my c++ study concerning references. It states the following rule:
Once a reference is initialized to an object, it cannot be changed to refer to another object.
Iv wrote a short code (as asked to in an exercise) that is meant to prove this rule correct.
int y = 7;
int z = 8;
int&r = y;
r = z;
Can someone explain why this code compiles without any errors or warnings?
r = z
does not change what r
"points to." It assigns the value of z
to the object pointed to by r
.
The following code does the same thing as your code, but using pointers instead of references:
int y = 7;
int z = 8;
int* p = &y; // p points to y
*p = z; // assign value of z to the object pointed to by p (which is y)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With