Return by reference in C++ with Examples
Pointers and References in C++ held close relation with one another. The major difference is that the pointers can be operated on like adding values whereas references are just an alias for another variable.
- Functions in C++ can return a reference as it’s returns a pointer.
- When function returns a reference it means it returns a implicit pointer.
Return by reference is very different from Call by reference. Functions behaves a very important role when variable or pointers are returned as reference.
See this function signature of Return by Reference Below:
dataType& functionName(parameters);
where,
dataType is the return type of the function,
and parameters are the passed arguments to it.
Below is the code to illustrate the Return by reference:
CPP
#include <iostream>
using namespace std;
int & returnValue( int & x)
{
cout << "x = " << x
<< " The address of x is "
<< &x << endl;
return x;
}
int main()
{
int a = 20;
int & b = returnValue(a);
cout << "a = " << a
<< " The address of a is "
<< &a << endl;
cout << "b = " << b
<< " The address of b is "
<< &b << endl;
returnValue(a) = 13;
cout << "a = " << a
<< " The address of a is "
<< &a << endl;
return 0;
}
|
Output:
x = 20 The address of x is 0x7fff3025711c
a = 20 The address of a is 0x7fff3025711c
b = 20 The address of b is 0x7fff3025711c
x = 20 The address of x is 0x7fff3025711c
a = 13 The address of a is 0x7fff3025711c
Explanation:
Since reference is nothing but an alias(synonym) of another variable, the address of a, b and x never changes.
Note: We should never return a local variable as a reference, reason being, as soon as the functions returns, local variable will be erased, however, we still will be left with a reference which might be a security bug in the code.
Below is the code to illustrate the Return by reference:
C++
#include <iostream>
using namespace std;
int x;
int & retByRef()
{
return x;
}
int main()
{
retByRef() = 10;
cout << x;
return 0;
}
|
Explanation:
Return type of the above function retByRef() is a reference of the variable x so value 10 will be assigned into the x.
Last Updated :
01 Aug, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...