Dremendo Tag Line

References in C++ Programming

Pointer and Structure in C++

In this lesson, we will understand what is References in C++ Programming and how to create them along with some examples.

What is References in C++?

References in C++ is an alias for another variable, meaning that when we declare a reference, we create a new name for an existing variable. We can access and modify the original variable's value using its reference variable.

A reference variable must be initialized when declared and cannot be changed to reference another variable once it is initialized.

video-poster

Example

#include <iostream>

using namespace std;

int main()
{
    // Declare an integer variable with the value 10
    int x = 10;

    // Declare a reference to the variable x
    int &y = x;

    // Print the value of x and y
    cout<<"x: "<<x<<", y: "<<y<<endl;

    // Change the value of x
    x=20;

    // Print the value of x and y again
    cout<<"x: "<<x<<", y: "<<y<<endl;

    // Change the value of y
    y=30;

    // Print the value of x and y once more
    cout<<"x: "<<x<<", y: "<<y<<endl;

    // Printing the address of x and y
    cout<<"Address of x = "<<&x<<endl;
    cout<<"Address of y = "<<&y<<endl;

    return 0;
}

Output

x: 10, y: 10
x: 20, y: 20
x: 30, y: 30
Address of x = 0x6dfed8
Address of y = 0x6dfed8

In the above example, the reference y is created for the variable x. It means that y is an alias (nickname) for x. If we make any changes to the value of y, it will also change the value of x (and vice versa).

We can see that when we change the value of x, the value of y is also changed, and when we change the value of y, the value of x is also changed because y is an alias for x. If we make any changes to the value of y, it will also change the value of x (and vice versa).

We can also see that the memory address of both variables is also same.

Pass reference to a function as parameter

We can also pass a reference to a function as a parameter to access the original variable inside the function. See the example given below.

Example

#include <iostream>

using namespace std;


void modify(int &a)
{
    a=a+10;
}

int main()
{
    int x=10;

    // Before modification
    cout<<"x="<<x<<endl;

    modify(x);

    // After modification
    cout<<"x="<<x<<endl;

    return 0;
}

Output

x=10
x=20

In the above program, we have declared a reference variable &a as a formal argument in the modify() function. We pass the variable x to the modify() function. Thus variable &a becomes an alias to the variable x. After that, the value of the variable a increments by 10. As variable a is an alias to variable x, the value is also changed in x.