C++ Tutorial: Passing arguments by reference and returning by reference.
Pass by Reference
Pass by reference in C++ is implemented as the variable aliasing. The function definition for pass by reference is defined as follow:
{
num++;
}
The call to this function is
incr(a);
Return by Reference
In C++, a function can be return a variable by reference. Like the variable alias in passing arguments as reference the return by reference returns the alias (actually the reference which does not need the dereferencing operator). It allows the function to be written on the left hand side of the equality expression. Using C style of returning the address, the function should return the address of the variable as:
{
if(*n1 > *n2)
return n1;
else
return n2;
}
The function is called as
*max(&a1, &a2) = 100;
The return by reference is simplified in C++ by using the alias mechanism. The function definition for return by reference is of the following form in C++
{
if(n1 > n2)
return n1;
else
return n2;
}
It is called as
max(a,b) = 100;
This example return the reference of the variables that are passed as reference to the function.