References in C++

What are references?

References are just aliases to the variable names i.e. an alternative name to our original variable name.
For example, int &ref = var;
Now ref is a reference (alias) of variable var. The variable var can be called by both names now, var and ref.
Let’s look at a code snippet,

    int var = 4;
    int &ref = var;     //ref is now a reference to var
    var++;          //var now has value 5
    ref++;          //var now has value 6 (ref acts just like var)
    cout << var;        //prints 6
    cout << ref;        //prints 6

This shows us that ref is just another name of var.

Some important points to note:

  1. When a reference variable is created, memory is not set aside for another variable. It is just an alias name for the original variable.

  2. Memory address of reference variable and original variable is same (point 1 only)

    int var = 4;
    int &ref = var;
    int *ptr1,*ptr2;
    ptr1 = &var;
    ptr2 = &ref;
    cout << ptr1 << endl;
    cout << ptr2 << endl;
    // both cout statements print the same thing only
    
  3. When (&) operator used on right side of equal to (=) works as address-of-operator and when used on left side works as reference operator.

  4. References should always be initialized.

    int &ref1 = var;        //OK!
    int &ref2;          //NOT OK!
    
  5. References cannot be reinitialized.

    int var1 = 2,var2 = 4;
    int &ref = var1;        //OK!
    ref = var2;         //NOT OK!
    

Calling Functions with References

#include <iostream>
using namespace std;

void swap(int &a, int &b)       //function to swap two numbers
{
    int tmp;
    tmp = a;
    a = b;
    b = tmp;
}

int main()
{
    int p = 3,q = 4;
    cout << p << “ ” << q << endl;      //before swapping
    swap(p,q);
    cout << p << “ ” << q << endl;      //after swapping
    return 0;
}

In the above function ‘a’ and ‘b’ are aliases (references) to ‘p’ and ‘q’ respectively. So this means values of ‘a’ and ‘b’ are not copied to ‘p’ and ‘q’ rather any changes made to the latter reflect to the former. That’s why it is called call by reference.
Output of the above program is

3 4  
4 3

Values are swapped!

Note: Calling functions with pointers also give us the same results, these are two different methods of achieving the same result.

Returning references from functions

double& maxEle(double &x, double &y)
{
    if (x > y)
        return x;
    else
        return y;
}

The above function accepts two references and returns a reference, not a value but a reference. It returns the reference of ‘x’ or ‘y’ depending on which is greater.

AUTHOR

READ NEXT

Boostlog is an online community for developers
who want to share ideas and grow each other.

Delete an article

Deleted articles are gone forever. Are you sure?