Search code examples
c++referencerules

Why does changing what a reference points to not throw an error?


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?


Solution

  • 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)