Javatpoint Logo
Javatpoint Logo

When do we pass arguments by reference or pointer?

Variables are passed by reference in C++ for the following reasons:

1) To change the caller function's local variables: A reference (or pointer) allows the called function to modify a caller function's local variable. Consider the following example programme, in which fun() can change the local variable x of main ().

C++ Code

Output:

New value of x is 20

2) When passing large arguments: When passing a large argument, passing by reference (or pointer) is more efficient because only an address is passed, not the entire object. Consider the following Employee class and the function printEmpDetails(), which prints Employee details.

C Code

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 is only true for struct and class variables because basic types like int, char, and so on have no efficiency advantage.

3) To avoid Object Slicing: If we pass a subclass object to a function that expects a superclass object, the passed object is sliced if it is passed by value. Consider the following programme, which prints "This is Pet Class."

C Code

Output:

This is Pet Class

When we use pass by reference in the above programme, it prints " This is Dog Class " correctly. See the modified programme below.

C++ Code

Output:

This is Dog Class

This is also not true for basic data types such as int, char, and so on.

4) Obtaining Run Time Polymorphism in a Function: By passing objects as references (or pointers) to a function, we can make it polymorphic. In the following programme, for example, print() receives a reference to the base class object. If a base class object is passed, the function print() calls the base class function show(), and if a derived class object is passed, the function show() is called.

C++ Code

Output:

In base 
In derived 

*Pointers have a value, and because function arguments in C++ are passed by value by default, when you use pointers, a copy of the pointer is passed to the function.

Conclusion

If an argument is large (such as a string that is a list), it is preferable to use pass by reference to avoid having to move the entire string. Passing by reference effectively passes only the address of the argument, not the argument itself.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA