When Do We Pass Arguments by Reference or Pointer in C++?
Last Updated :
25 Jan, 2024
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 in C++
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.
Syntax to Declare Pointer
data_type * pointer_name = &some_variable;
To learn more about pointers, visit the article - C++ Pointers
References in C++
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.
Syntax to Declare References
data_type &ref = variable;
To learn more about pointers, visit the article -C++ References
When to Pass Arguments by Reference or Pointer in C++?
In C++, arguments are passed by reference or pointer in the following cases:
1. To Modify the Local Variable of the Caller Function
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
C++
// C++ program to modify local variables of the caller
// function
#include <iostream>
using namespace std;
// function to modify local variable a
void fun(int* ptr) { *ptr = 4; }
// driver code
int main()
{
int num = 2;
cout << "Old value of a is " << num << endl;
fun(&num);
cout << "New value of a is " << num << endl;
return 0;
}
OutputOld value of a is 2
New value of a is 4
2. Avoiding Copy of Large Data
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
C++
// C++ program to show how to pass the structure as a
// reference to a function
#include <iostream>
using namespace std;
// Structure to represent Intern
struct Intern {
string name;
string company;
};
// Function to print Intern details
void printInDetails(const Intern& it)
{
cout << "Name: " << it.name << endl;
cout << "Company: " << it.company << endl;
}
int main()
{
// Creating an instance of Intern
Intern it1 = { "Abhishek", "GeekforGeeks" };
printInDetails(it1);
return 0;
}
OutputName: Abhishek
Company: GeekforGeeks
3. To Achieve Run Time Polymorphism in a Function
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:
C++
#include <iostream>
using namespace std;
// Define the base class structure
struct Base {
virtual void show() { cout << "In base\n"; }
};
// Define the derived class structure
struct Derived : public Base {
// Override for Derived behavior
void show() override { cout << "In derived\n"; }
};
// Function to print using polymorphism
void print(Base* base) { base->show(); }
// driver code
int main(void)
{
Base b;
Derived d;
print(&b);
print(&d);
return 0;
}
4. To Return Multiple Values
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:
C++
#include <iostream>
using namespace std;
// Function to calculate sum and difference of two numbers
void calcSumAndDifference(int x, int y, int* sum, int* diff)
{
*sum = x + y;
*diff = x - y;
}
int main()
{
int x = 4;
int y = 2;
int sum, diff;
// calling the function to calculate sum and difference
calcSumAndDifference(x, y, &sum, &diff);
// printing the sum and difference returned from function
cout << "Sum is: " << sum << endl;
cout << "Difference is: " << diff << endl;
return 0;
}
OutputSum is: 6
Difference is: 2
Similar Reads
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++? Let's first understand what Passing by Pointer and Passing by Reference in C++ mean: Passing
5 min read
Pointers and References in C++
In C++ pointers and references both are mechanisms used to deal with memory, memory address, and data in a program. Pointers are used to store the memory address of another variable whereas references are used to create an alias for an already existing variable. Pointers in C++ Pointers in C++ are a
5 min read
Passing Map as Reference in C++ STL
Prerequisite: Maps in C++ STL Pass by reference Elements in the map are in form of pairs where the first is key and another value, denoting key-value pairs. Also, all the key values are unique means no two elements can have the same key value. Passing maps by value is a costly task, costly in terms
3 min read
Pass By Reference In C
Passing by reference is a technique for passing parameters to a function. It is also known as call by reference, call by pointers, and pass by pointers. In this article, we will discuss this technique and how to implement it in our C program. Pass By Reference in C In this method, the address of an
4 min read
Pass by Value and Pass by Reference in Javascript
JavaScript handles variables in different ways when passing them to functions. Variables in JavaScript can either be passed by value or passed by reference, depending on the type of data they hold. "Pass by Value" in JavaScriptWhen a variable is passed by value, a copy of the actual value is passed
3 min read
Pointers vs References in C++
Prerequisite: Pointers, References C and C++ support pointers, which is different from most other programming languages such as Java, Python, Ruby, Perl and PHP as they only support references. But interestingly, C++, along with pointers, also supports references. On the surface, both references and
5 min read
What are Reference Collapsing Rules in C++?
In C++, we have a very useful feature called reference collapsing, which comes into play when dealing with references to references, especially in the context of templates. It is very important to make templates work seamlessly with references, ensuring that code behaves consistently and as expected
4 min read
Default Assignment Operator and References in C++
We have discussed assignment operator overloading for dynamically allocated resources here. In this article, we discussed that when we don't write our own assignment operator, the compiler creates an assignment operator itself that does shallow copy and thus causes problems. The difference between s
2 min read
Different Ways to Achieve Pass By Reference in Java
There are two types of parameters one is Formal parameters and the second is Actual Parameters. Formal parameters are those parameters that are defined during function definition and Actual parameters are those which are passed during the function call in other Function. Showcasing the formal and ac
5 min read
Perl | Pass By Reference
When a variable is passed by reference function operates on original data in the function. Passing by reference allows the function to change the original value of a variable. When the values of the elements in the argument arrays @_ are changed, the values of the corresponding arguments will also c
2 min read