Consider this:
1 2 3 4 5 6
|
int *p; // p is a pointer to int
int x = 0; // x is an int
p = &x; // p is now pointing to x
int &r = x; // r is a reference to x
int y = 0;
p = &y; // p is now pointing to y
|
We start off declaring p, but not initialising it. We can change the value of p, so it points to x, we can also change it again, so it points to some other int (y).
r is a reference to x. We can never make r refer to anything else, it is a reference to x forever.
r cannot be naked, it must always refer to something. You can have a dangling pointer, like
int *p;
But you can not have a dangling reference like:
int &r; // no!
To use or change the value pointed to you need to de-reference a pointer:
1 2 3
|
int x = 0;
int *p = &x; // notice you assign the address of x to the pointer, not x itself
*p = 1; // de-reference the pointer, now x == 1;
|
To use a reference, there is no de-referencing semantic
1 2 3
|
int x = 0;
int &r = x; // notice you don't have to use the address of x
r = 1; // no need to de-reference, now x == 1
|
If it helps, you may think of a reference as a pointer that is automatically de-referenced
Note you can't make a reference refer to something else. For example:
1 2 3 4
|
int x = 1;
int &r =x;
int y = 2;
r = y; // this does not make r refer to y, it just assigns the value of y to x, now x == y
|