In C++, we can pass parameters to a function either by pointers or by reference. In both the cases, we get the same result. So the following questions are inevitable; when is one preferred over the other? What are the reasons we use one over the other?
Passing by Pointer:
Before Swap a = 45 b = 35 After Swap with pass by pointer a = 35 b = 45
Passing by Reference:
Before Swap a = 45 b = 35 After Swap with pass by reference a = 35 b = 45
Difference in Reference variable and pointer variable
References are generally implemented using pointers. A reference is same object, just with a different name and reference must refer to an object. Since references can’t be NULL, they are safer to use.
- A pointer can be re-assigned while reference cannot, and must be assigned at initialization only.
- Pointer can be assigned NULL directly, whereas reference cannot.
- Pointers can iterate over an array, we can use ++ to go to the next item that a pointer is pointing to.
- A pointer is a variable that holds a memory address. A reference has the same memory address as the item it references.
- A pointer to a class/struct uses ‘->'(arrow operator) to access it’s members whereas a reference uses a ‘.'(dot operator)
- A pointer needs to be dereferenced with * to access the memory location it points to, whereas a reference can be used directly.
Output (May be different in different runs as we print addresses in program):
0x7ffd09172c20 0x7ffd09172c18 0x7ffd09172c18 0x7ffd09172c18 0x4 7
Usage in parameter passing:
References are usually preferred over pointers whenever we don’t need “reseating”.
Overall, Use references when you can, and pointers when you have to. But if we want to write C code that compiles with both C and a C++ compiler, you’ll have to restrict yourself to using pointers.
This article is contributed by Rohit Kasle. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Passing Reference to a Pointer in C++
- Passing NULL to printf in C
- How to delete an element from the Set by passing its value in C++
- Passing and Returning Objects in C++
- Passing a vector to constructor in C++
- Passing vector to a function in C++
- Parameter Passing Techniques in C/C++
- Reference to a pointer in C++ with examples and applications
- When do we pass arguments by reference or pointer?
- Equation of straight line passing through a given point which bisects it into two equal line segments
- Double Pointer (Pointer to Pointer) in C
- Output of the program | Dereference, Reference, Dereference, Reference....
- What is a Pointer to a Null pointer
- Can C++ reference member be declared without being initialized with declaration?
- 'this' pointer in C++