In C++, variables are passed by reference due to following reasons:
1) To modify local variables of the caller function: A reference (or pointer) allows called function to modify a local variable of the caller function. For example, consider the following example program where fun() is able to modify local variable x of main().
New value of x is 20
2) For passing large sized arguments: If an argument is large, passing by reference (or pointer) is more efficient because only an address is really passed, not the entire object. For example, let us consider the following Employee class and a function printEmpDetails() that prints Employee details.
The problem with above code is: every time printEmpDetails() is called, a new Employee object is constructed that involves creating a copy of all data members. So a better implementation would be to pass Employee as a reference.
This point is valid only for struct and class variables as we don’t get any efficiency advantage for basic types like int, char.. etc.
3) To avoid Object Slicing: If we pass an object of subclass to a function that expects an object of superclass then the passed object is sliced if it is pass by value. For example, consider the following program, it prints “This is Pet Class”.
This is Pet Class
If we use pass by reference in the above program then it correctly prints “This is Dog Class”. See the following modified program.
This is Dog Class
This point is also not valid for basic data types like int, char, .. etc.
4) To achieve Run Time Polymorphism in a function
We can make a function polymorphic by passing objects as reference (or pointer) to it. For example, in the following program, print() receives a reference to the base class object. print() calls the base class function show() if base class object is passed, and derived class function show() if derived class object is passed.
Thanks to Venki for adding this point.
As a side note, it is a recommended practice to make reference arguments const if they are being passed by reference only due to reason no. 2 or 3 mentioned above. This is recommended to avoid unexpected modifications to the objects.
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++
- Reference to a pointer in C++ with examples and applications
- Passing by pointer Vs Passing by Reference in C++
- Double Pointer (Pointer to Pointer) in C
- Output of the program | Dereference, Reference, Dereference, Reference....
- What is a Pointer to a Null pointer
- How to pass an array by value in C ?
- Default Arguments in C++
- How to pass a 2D array as a parameter in C?
- Templates and Default Arguments
- Command line arguments in C/C++
- Command line arguments example in C
- Default arguments and virtual function
- Some Interesting facts about default arguments in C++
- Variable length arguments for Macros