![]() |
VOOZH | about |
In C++, we can pass arguments to a function as a value, reference (or pointer). Each method has its unique benefits and uses. In this article, we will discuss the application or cases where we should pass the arguments by reference or a pointer. But first, let’s quickly revisit the definitions of pointers and references.
Pointers are symbolic representations of addresses. They are the variables that store the memory address of the data. The address of the variable you’re working with is assigned to the pointer variable that points to the same data type (such as an int or string).
We can use the pointers to pass arguments address to the function i.e. pass by pointer method.
data_type * pointer_name = &some_variable;
To learn more about pointers, visit the article - C++ Pointers
When a variable is declared as a reference, it becomes an alternative name for an existing variable. A variable can be declared as a reference by putting ‘&’ in the declaration. They are similar to pointers in the way that ‘&’ is used for signifying the address of a variable or any memory. The difference is that we don't need to use *(dereference operator) to access the value of the reference. We can use the reference name to directly access the value.
data_type &ref = variable;
To learn more about pointers, visit the article -C++ References
In C++, arguments are passed by reference or pointer in the following cases:
A reference (or pointer) allows a called function to modify the local variables of the caller function that are passed as the arguments. This means that a function can modify a variable in the calling function by using a pointer to that variable.
Example
Old value of a is 2 New value of a is 4
Imagine a function that has to receive a large-sized object, if we pass it without reference, a new copy of it is created which causes a waste of CPU time and memory. We can use references or pointers to avoid this.
Example
Name: Abhishek Company: GeekforGeeks
We can make a function polymorphic by passing objects as references (or pointers) to it instead of the actual objects. It allows us to achieve runtime polymorphism in our program.
Example:
In base In derived
When we want to return multiple values from a function, passing pointers as function parameters allows us to modify the values of variables passed to the function.
Example:
Sum is: 6 Difference is: 2