Getting back to pointers vs. references. a reference is a
synonym for another object. In other words, it's just a different name for some object.
A pointer is a type of variable that contains the address of another object.
A reference may be implemented with a pointer, but it doesn't have to be:
1 2
|
int A; // compiler knows where A is
int &B(A); // Compiler knows where B is too. No need for a pointer.
|
When you think of a reference as a synonym for another object, some of the subtle points become obvious:
- taking the address of a reference takes the address of the other object.
- Assigning something to a reference changes the object.
- You can't change a reference to refer to another object, anymore than you can change
int x
to somehow refer to a different integer.
And since a pointer is a variable like any other:
- taking the address of a pointer takes the address of the pointer itself, not the thing it points to.
- Assigning something to a pointer causes it to point to somewhere else.
- The above means that you can change a pointer to point to different objects at runtime.