Can I make a reference refer to a different object?
No, we cannot. The reference itself has no identity, it’s not an object. The reference and the referent are the same. Hence a reference cannot be made to point to any other object unlike a pointer which can be used for that purpose.References are usually preferred over pointers whenever you don't need them to point to any other object.
An example that illustrates the above concept:
- include <iostream.h>
int main()
{
int firstInt;
int &myRef = firstInt;
firstInt = 4;
cout << "firstInt:\t" << firstInt << endl;
cout << "myRef:\t" << myRef << endl;
cout << "&firstInt:\t" << &firstInt << endl;
cout << "&myRef:\t" << &myRef << endl;
int secondInt = 9;
myRef = secondInt; // not what you think!
cout << "\nfirstInt:\t" << firstInt << endl;
cout << "secondInt:\t" << secondInt << endl;
cout << "myRef:\t" << myRef << endl;
cout << "&firstInt:\t" << &firstInt << endl;
cout << "&secondInt:\t" << &secondInt << endl;
cout << "&myRef:\t" << &myRef << endl;
return 0;
}
In the above code snippet, a variable, firstInt is created and a reference, myRef is initialized to firstInt. The value 4 is assigned to firstInt, and thus indirectly to myRef. These are printed. secondInt is created and initialized with the value 9 and then comes the important line:
myRef = secondInt;
It is tempting to believe that the result of this assignment will be that firstInt will remain 4, secondInt will remain 9 and myRef will have the value
9. Unfortunately, that is not what will happen. myRef is and remains a reference to firstInt, so writing
myRef = secondInt;
is exactly like writing:
firstInt = secondInt;
The result is that all three values are 9. Here is how the output looks:
firstInt: 4
myRef: 4
&firstInt: 0x0012FF7C
&myRef: 0x0012FF7C
firstInt: 9
secondInt: 9
myRef: 9
&firstInt: 0x0012FF7C
&secondInt: 0x0012FF74
&myRef: 0x0012FF7C
What is critical here is to note that the address returned by &firstInt and &myRef are the same; myRef is an alias for firstInt and when you ask it for its address you get the address of the object it refers to.
What is critical here is to note that the address returned by &intOne and &someRef are the same -- remember, someRef is an alias for intOne and when you ask it for its address you get the address of the object it refers to. It is as if someRef said "Oh, I'm unimportant, sir. The one you want is the most esteemed intOne."
C++ FAQ Home