I just don't get the C++ Pointer/Reference system
Doesn't & mean "memory address of" x in C++?
Short answer: That depends.
Longer answer: The unary prefix operator &
, when applied to an object, indeed yields the address of the object: &obj
. There is, however, also the type modifier &
, which, when applied to a type, will modify it to be a reference type: int&
.
The same applies to *
: When used as a unary prefix operator, it will dereference a pointer: *ptr
. When used as a type modifier, it will modify the type to be a pointer: int*
.
It's not helpful either that type modifiers apply to the variable that is declared. For example, this
int *p, **pp, i, &r = i;
defines an int
pointer, a pointer to a pointer to an int
, a vanilla int
, and an int
reference. (The latter is immediately initialized, because you cannot have an uninitialized reference.) Note that the type modifiers syntactically belong to the declared variable whose type they are modifying, not to the declared variable's type. Nevertheless, type modifiers (*
and &
) modify the type of the variable.
In the following case, however, with pp
and i
presumed to be variables that have already been declared
*pp = &i;
*
and &
are unary prefix operators dereferencing pp
and yielding the address of i
.
(In the same vein, the type modifier []
when applied to a variable that's being declared, will modify the variable's type to an array, while the binary infix operator []
, when applied to an object of array type will access one of its sub-objects.)
To complicate things even further, besides the type modifiers and the unary prefix operators &
and *
, there are also the binary infix operators &
and *
, meaning "bitwise AND" and "multiplication". And to add insult to injury, in C++ you can overload both the unary prefix and the binary infix variants of these operators (and the binary infix []
) for user-defined types and be completely free as to their semantics.
In the first example, &
is used to declare a reference type.
It's not the same thing as the &
operator which is used to get an object's address.
You can view a reference type as a type which uses under the covers a pointer which can never be NULL
.
Actually, the &-operator serves two purposes as posted above.
the first purpose is dereference, which is used like this:
int i = 123; //declare an integer variable named i with the value of 123
int *pI = &i; //declare an pointer-to-integer
//variable name pI pointing to the memory address of i
The &-operator is used in the meaning 'give me the memory address of'
the second purpose is to emulate call-by-reference (which c does not have natively)
a declaration like
void foo(int& theInt)
{
theInt = 123;
}
will make the function foo accept an int parameter, to which any modification during the execution of foo is passed back.
Without the &-operator, modifications to theInt would be made in the foo's scope only and discarded once the function terminates.