Return by reference in c++
A reference on a general note is represented by the ampersand symbol which looks like (&) in the programming language C++ and is considered to be an alias or copy of the original variable. In C++, a shallow copy is generally made in order to create a reference variable, which usually implies that the reference variable points towards the address of the original variable, and if any changes will be made to the reference variable then that will be reflected in the original variable. For e.g., if we take b to be a shallow copy of a, then if we will change the value of b, then the value of a is also going to be changed as b is going to have the same address as that of a.
The following syntax can be used to create any reference variable of our choice,int& ri_reference_var=ri_orginal_var;
The ampersand denotes that the variable present here is a reference variable and the ri_original_var is our variable for which the ri_reference_var is getting referenced. The reference variable is supposed to be initialized while declaration of the variable. That’s why, our declaration int& ri_variable; is likely to result in a possible error.
The return by reference concept of the language C++ is generally used for creating a function that is going to return a reference to the our original variable.
The syntax for the function which is supposed to return by reference in c++s,
return by reference in c++
The data_type& in the code generally represents that the returned variable is going to be a reference variable of the present C++ data type data_type.
The data_type& original_variable in the code generally represents that a reference variable which is named original_variable is going to be created to the variable which is passed as a parameter to our function.
The return original_varible is going to return our created reference variable and is supposed to mark the end of our function.
In the syntax present above, a normal variable is being passed to our function and a different reference variable or can be called an implicit pointer to the original variable is being generated and then returned by the function. That’s why it gets important to remember that the property of reference is applied in both of the return statement and the argument that is being passed to the function.
Considering the following case,
ere ri_oringinal_vaiable can be treated as a normal variable. After passing this to our function, below is the result that occurs,int& ri_original_varaible_ref=ri_original_variable;
A reference variable gets created here and then returned by the function.
The algorithm for the return reference function in the language C++ is going to be as follows,
- Declare the desired function with the required return type and parameter in the form of reference variables.
- Perform the desired actions taking the reference variable inside of the function.
- After that return the reference variable.
- Call Your function.
return by reference in c++