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 is the difference between Passing by Pointer and Passing by Reference in C++?
Lets first understand what Passing by Pointer and Passing by Reference in C++ mean:
1) Passing by Pointer: Here, the memory location of the variables is passed to the parameters in the function, and then the operations are performed.
Before Swap a = 45 b = 35 After Swap with pass by pointer a = 35 b = 45
2) Passing by Reference: It allows a function to modify a variable without having to create a copy of it. We have to declare reference variables. The memory location of the passed variable and parameter is the same and therefore, any change to the parameter reflects in the variable as well.
Before Swap a = 45 b = 35 After Swap with pass by reference a = 35 b = 45
Difference Between Reference Variable and Pointer Variable:
A reference is the same object, just with a different name and a reference must refer to an object. Since references can’t be NULL, they are safer to use.
- A pointer can be re-assigned while a reference cannot, and must be assigned at initialization only.
- The pointer can be assigned NULL directly, whereas the reference cannot.
- Pointers can iterate over an array, we can use increment/decrement operators to go to the next/previous 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 its 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.
The following example demonstrates the differences:
0x7ffc7ed95828 0x7ffc7ed95820 0x7ffc7ed95820 0x7ffc7ed95820 0x4 7
Which is preferred in Passing by Pointer Vs Passing by Reference in C++?
- 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.