References in C++

A reference is an alternate name to an existing variable. References are often confused with pointers but there are major differences between references and pointers.

  • References cannot be NULL. We must always assume that a reference is connected to a legitimate piece of storage.
  • References must be initialized when they are created but pointers can be initialized at any time.
  • Once a reference is initialized, references cannot be changed to refer to another object but pointers can be initialized and pointed to another object at any time.

How to create a reference in C++?

Reference can be created by using an ampersand (&) operator. When we create a variable, it occupies the memory location. We can create a reference of the variable so that we can access the original variable by using either the name of the variable or reference.

Example

int i = 17; 
int &ref = i; //Now, we create the reference variable for i 

In the above exanmple, 'ref' is a reference variable of 'i'. We can use the 'ref' variable in place of the 'i' variable.

Types of References in C++

In C++, there are two types of references:

  1. References as aliases - It is the other name of the variable which is being referenced.
  2. 
    #include <iostream>  
    using namespace std; 
    
    int main()  
    {  
      int i=74; // variable initialization  
      int &j=i;  
      int &k=i;  
      cout << "Value of i is :" << i << "\n";
      cout << "Value of j is :" << j << "\n";
      cout << "Value of k is :" << k << "\n"; 
      return 0;
    } 
    
    Output
    Value of i is :74
    Value of j is :74
    Value of k is :74

    In the above example, we created a variable 'i' which contains a value '74'. We have declared two reference variables, that is 'j' and 'k', and both are referring to the same variable 'i'. Therefore, we can say that the 'i' variable can be accessed by 'j' and 'k' variables.

  3. References to non-const values - It can be declared by using & operator with the reference type variable.
  4. 
    #include <iostream>
    using namespace std;
    int main()
    {
      int i = 17;
      int &value = i;
      cout << value;
      return 0;
    }
    
    Output
    17