Differences between pointers and references in C++
A pointer in C++ is a variable that holds the memory address of another variable.
A reference is an alias for an already existing variable. Once a reference is initialized to a variable, it cannot be changed to refer to another variable.
Pointer
-
It is not necessary to initialize it with a value during declaration.
int a = 5; int *p; p = &a; -
It can be assigned a NULL value.
-
It must be dereferenced with a
*to access the variable’s value.
-
Arithmetic operations can be performed on it.
-
After declaration, it can be re-assigned to any other variable of the same type.
int a = 5; int *p; p = &a; int b = 6; p = &b;
Reference
-
It is necessary to initialize it with a value during declaration.
int a = 5; int &ref = a; -
It cannot be NULL.
-
It does not need to be dereferenced and can be used simply by name.
-
Arithmetic operations can not be performed on it.
-
It cannot be re-assigned to any other variable after its initialization.
Free Resources