Pointers vs References
Pointers vs References in C++: This article lays the proper ground for differences between Pointer and references. Both references and pointers can be used to change the local variables of one function inside another function. Both of them can also be used to save copying of big objects when passed as arguments to functions or returned from functions, to get efficiency gain.
Despite the above similarities, there are the following differences between references and pointers.
Note A pointer can be declared as void but a reference can never be void.For example:
int a = 10;
void*aa = &a;. //it is valid
void &ar = a; // it is not valid
- References are less powerful than pointers
- Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.
- References cannot be NULL. Pointers are often made NULL to indicate that they are not pointing to any valid thing.
- A reference must be initialized when declared. There is no such restriction with pointers
- Passing by pointer Vs Passing by Reference in C++: In C++, we can pass parameters to a function either by pointers or by reference. In both cases, we get the same result. So what should be preferred and why?
- Passing Reference to a Pointer in C++: In this article let’s compare the usage of a “pointer to pointer” VS “Reference to pointer” in some cases.
Pointers and References in C++
In C++ pointers and references both are mechanisms used to deal with memory, memory address, and data in a program. Pointers are used to store the memory address of another variable whereas references are used to create an alias for an already existing variable.