Reputation: 2496
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.
Upvotes: 1
Views: 156
Reputation: 54276
The line
int & rodents = *pt;
is creating a reference to what pt
is pointing to (i.e. rats
). It's not a reference to the pointer pt
.
Later, when you assign pt
to point to bunnies
, you would not expect the rodents
reference to change.
EDIT: To illustrate @Als point, consider the following code:
int value1 = 10;
int value2 = 20;
int& reference = value1;
cout << reference << endl; // Prints 10
reference = value2; // Doesn't do what you might think
cout << reference << endl; // Prints 20
cout << value1 << endl; // Also prints 20
The second reference
assignment does not change the reference ltself. Instead, it applies the assignment operator (=
) to the thing referred to, which is value1
.
reference
will always refer to value1
and 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.
Upvotes: 2