Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 284
Bap Johnston Avatar asked Nov 30 '22 08:11

Bap Johnston


1 Answers

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)
like image 130
James McNellis Avatar answered Dec 05 '22 07:12

James McNellis