I have a pointer which is pointing to an integer variable. Then I assign this pointer to a reference variable. Now when I change my pointer to point some other integer variable, the value of the reference variable doesn’t change. Can anyone explain why?
int rats = 101;
int * pt = &rats;
int & rodents = *pt; // outputs
cout << "rats = " << rats; // 101
cout << ", *pt = " << *pt; // 101
cout << ", rodents = " << rodents << endl; // 101
cout << "rats address = " << &rats; // 0027f940
cout << ", rodents address = " << &rodents << endl; // 0027f940
int bunnies = 50;
pt = &bunnies;
cout << "bunnies = " << bunnies; // 50
cout << ", rats = " << rats; // 101
cout << ", *pt = " << *pt; // 50
cout << ", rodents = " << rodents << endl; // 101
cout << "bunnies address = " << &bunnies; // 0027f91c
cout << ", rodents address = " << &rodents << endl; // 0027f940
We assigned pt to bunnies, but the value of rodents is still 101. Please explain why.
The line
is creating a reference to what
ptis pointing to (i.e.rats). It’s not a reference to the pointerpt.Later, when you assign
ptto point tobunnies, you would not expect therodentsreference to change.EDIT: To illustrate @Als point, consider the following code:
The second
referenceassignment does not change the reference ltself. Instead, it applies the assignment operator (=) to the thing referred to, which isvalue1.referencewill always refer tovalue1and cannot be changed.It’s a little tricky to get your head around at first, so I recommend you take a look at Scott Meyer’s excellent books Effective C++ and More Effective C++. He explains all this much better than I can.