References In C++

Get To Know The Ways To Declare And Use References In C++.

Reference is a major concept in C++ programming language. Although it’s not as strong as pointers, nonetheless it allows us to use it to write efficient programs. The major use of the reference variable is in passing parameters to functions.

The popular ‘pass by reference’ parameter passing technique makes use of references. In this tutorial, we will see what a reference is, and how to declare & use it. We will also discuss the differences between pointers and references as well as passing and returning a reference to/from functions.

=> See Here To Explore The Full C++ Tutorials list.

References in C++

What Is A Reference?

Reference is an alias or another name for a variable. Given a variable with an identifier, we can provide another identifier to this variable so that we can refer to this variable either with its original name or another name. This ‘another name’ is what is called as a Reference.

Consider we have a variable ‘i’ with value 17. If j is a reference, then the memory representation of variable i and reference j is shown below.

reference - memory representation

As shown in the above figure, a variable and it's alias i.e. reference point to the same value.

Declaring Reference Variables

A reference can be declared using the ‘&’ operator.

The declaration of reference is shown below.

int a = 10;
int& refvar = a;

So in the above code, we have declared an integer variable with value 10. Then we declare another variable refvar and assign a variable to it. Note that while declaring refvar, we have used & operator just before the variable name. This indicates refvar is a reference to an already existing variable.

We can refer to the variable ‘a’ either by using the variable name a or using the reference name ‘refvar’.

Given below is a simple Example of References:

#include <iostream>
#include <string>
using namespace std;

int main()
{
  int age = 22;
  int& numYears = age;
  
  double salary = 10000.00;
  double& wages = salary;
  
  cout<<"Age: "<<age<<endl;
  cout<<"NumYears: "<<numYears<<endl;
  cout<<"Salary: "<<salary<<endl;
  cout<<"Wages: "<<wages<<endl;
  return 0;
}

Output:

Age: 22
NumYears: 22
Salary: 10000
Wages: 10000

In the above code, we have an integer variable age. Next, we declare a reference integer variable numYears to the age variable. We have another variable salary of type double. Next, we declare a double reference variable wages to the variable salary.

Next, we print the variables, first age then its reference is followed by salary and its reference. If we check the output of the program, we understand that variable and reference to it points to the same value and hence Age and numYears, as well as salary and wages, have the same values.

Reference Vs Pointers

When compared to pointers, references are safer and easier to use.

We will discuss a few differences between pointers and references:

  • Unlike pointers, references cannot have a null value. It is mandatory for references to have a value assigned to it.
  • References are initialized the moment they are created. Unlike this, pointers can be initialized at any point of time and not necessarily during declaration.
  • Pointers can be reassigned to the values at ease. But with references, we cannot do this. Once a value of the variable is assigned, i.e. once an alias of a variable is created, we cannot assign another variable to this reference.
  • We do not have void references. By definition, a reference is an alias for the variable and it is initialized during the creation itself. Thus, there is no chance that we will have void reference and later on assign a variable with a concrete data type to it. In contrast, we can have void pointers.

Due to these limitation discussed above, the references in C++ cannot be used with data structures like a linked list. Please note that in Java, we do not have all these restrictions or limitation on references.

Passing References To Functions

In our previous tutorials on functions, we have already discussed the ‘pass by reference’ parameter technique and we have seen the swapping of two numbers example using this technique. We skip the explanation of this technique in this section and only present a swap function once again as an example.

But this time instead of swapping numbers we are going to swap two strings.

#include<iostream> 
#include <string>
using namespace std; 
void swap(char * &str1, char * &str2) 
{ 
  char *temp = str1; 
  str1 = str2; 
  str2 = temp; 
} 
int main() 
{ 
  char *str1 = "references"; 
  char *str2 = "pointers"; 
  cout<<"str1 = "<<str1<<"\t"<<"str2 = "<<str2<<endl;
  swap(str1, str2); 
  cout<<"After swap...."<<endl;
  cout<<"str1 = "<<str1<<"\t"<<"str2 = "<<str2<<endl;
  return 0; 
}

Output:

str1 = references str2 = pointers
After swap….
str1 = pointers str2 = references

So in this program, we pass strings (char*) to the swap function. The formal parameters are two references to a variable of type char*. We note that when two values are swapped, their modification is reflected in the calling function as we are using references/aliases for parameters.

Returning References

Just like returning pointers from functions, we can also return references from functions. Returning references from a function also return an implicit pointer to the return value. Because of this reason, a function returning a reference can be used on the left-hand side of the assignment.

Let us an Example of returning a reference from a function.

#include <iostream>
using namespace std;

int myarray[] = {1, 0, 2, 3, 5};

int& setValues( int i ) //returns reference to the array
 {
    return myarray[i];
 }

int main ()
 {
   cout << "myarray before change" << endl;
   for ( int i = 0; i < 5; i++ )
 {
cout << "myarray[" << i << "] = ";
cout << myarray[i] << endl;
}

setValues(1) = 1;
setValues(3) = 8;
cout << "Value after change" << endl;
for (int i = 0; i < 5; i++ )
 {
   cout<< "myarray[" << i << "] = ";
   cout << myarray[i] << endl;
 }
return 0;
}

Output:

myarray before change
myarray[0] = 1
myarray[1] = 0
myarray[2] = 2
myarray[3] = 3
myarray[4] = 5
Value after change
myarray [0] = 1
myarray[1] = 1
myarray[2] = 2
myarray[3] = 8
myarray[4] = 5

Screenshot for the same is shown below:

return_reference

As seen in the above code, we define a function setValues that return a reference and a parameter which is an integer. Inside the function, we just return the array reference to the position I in C++.

In the main function, we print the values of the array. Then using the setValues function, we change the values of two elements in the array. Again we print the value of the array.

One thing that we must note with references is that we can have a function return a reference only when the data is either static or global. It is illegal to return a reference to a local variable in C++.

Conclusion

Readers should note that the main use of references is for passing parameters to functions.

In the upcoming tutorials, we will cover lambda functions/expressions in C++ before we jump to object-oriented programming in C++.

=> Check Out The Best C++ Training Tutorials Here.