Table of contents
1.
Introduction
2.
Creating References in C++
3.
Types of References
3.1.
References to Non-Const Values
3.2.
C++
3.3.
References As Aliases
4.
Applications of Reference in C++
5.
Properties of References
5.1.
Initialization
5.2.
C++
5.3.
Reassignment
5.4.
C++
5.5.
Function Parameter
5.6.
C++
5.7.
References as Shortcuts
5.8.
C++
6.
References VS Pointers
7.
Limitations of References in C++
8.
Advantages of Using References in C++
9.
Frequently Asked Questions
9.1.
What is the reference variable in C++?
9.2.
What does "by reference" mean in C++?
9.3.
What is a reference type in C++?
10.
Conclusion
Last Updated: Nov 7, 2024
Easy

Reference in C++

Author RAJESH RUNIWAL
2 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In C++, references are an essential feature that enables direct access to the memory location of a variable, making it easier to manipulate data without duplicating it. Unlike pointers, references provide a safer, more straightforward way to handle variables, particularly when passing them between functions or working with complex data structures. Using references can improve code efficiency, clarity, and performance, especially in memory-intensive applications. In this blog, we’ll explore the concept of references in C++.

Reference in C++

Creating References in C++

Reference can be created by certainly using an & operator. When we create a variable, it occupies some memory location. We will access the original variable using either name of the variable or reference. for example,

int a=10;

Now, we create a reference variable for the above variable.
 

int &reference=a;

The above declaration means that ‘ref’ is a reference variable of ‘a’, i.e., we can use the ‘ref’ variable instead of the ‘a’ variable.

Types of References

C++ provides two types of references:

1. References to non-const values

2. References as aliases

References to Non-Const Values

It can be declared by using & an operator with the reference type variable.

  • C++

C++

#include <bits/stdc++.h>
using namespace std;
int main() 

int a=10; 
int &value=a; 
cout << value << endl; 
return 0; 
You can also try this code with Online C++ Compiler
Run Code

Output

10 

References As Aliases

It is another name of the variable which is being referenced.

For example,

int x=10; // 'x' is a variable.  
int &y=x; // 'y' reference to x.  
int &z=x; // 'z' reference to x.  

Applications of Reference in C++

References in C++ have several practical applications that make code more efficient, readable, and less error-prone. Here are some common uses:

  • Function Parameters (Pass by Reference)
    Passing parameters by reference allows functions to modify the original variables without creating copies. This is especially useful for large data structures, as it saves memory and improves performance.
  • Returning Values by Reference
    Returning by reference can be useful when you want a function to return a reference to an existing variable, enabling direct modification of the original data rather than working on a copy.
  • Avoiding Copying in Large Structures
    For large data types, passing by reference avoids copying, which saves memory and speeds up the program. This is commonly used in handling objects or complex structures.
  • Operator Overloading
    References are essential in operator overloading, where they allow overloading operators like +, -, = etc., to work efficiently with objects without creating unnecessary copies.
  • Implementing Swap Functions
    By using references, you can directly swap two variables' values without creating additional variables or copying data.
  • Const References for Read-Only Access
    Const references allow read-only access to variables or objects, making the intention clear that the function won't modify the data, while also avoiding the performance cost of copying large objects.

 

Properties of References

Initialization

It will be initialized at the time of the declaration.

  • C++

C++

#include <bits/stdc++.h>
using namespace std;
int main() 

int a=20;
int &b=a;
cout << "value of a is " <<b<< endl; 
return 0; 
}
You can also try this code with Online C++ Compiler
Run Code

  

Output

value of a is 20 

Reassignment

It can’t be a reassigned method that is the reference variable cannot be modified.

  • C++

C++

#include <bits/stdc++.h>
using namespace std;
int main() 

   int x=11;
   int z=67; 
   int &y=x;
   cout<<"Address Before Reassingemnt "<<&y<<endl;
   y=z;
   cout<<"Address After Reassingemnt "<<&y<<endl;
   return 0;
}
You can also try this code with Online C++ Compiler
Run Code

  

Output

Address Before Reassingemnt 0x7ffe25f37748
Address After Reassingemnt 0x7ffe25f37748

Here we changed reference but still the address of y is same.

Function Parameter

References also can be passed as a function parameter. It does not create a copy of the argument and behaves as an alias for a parameter. It complements the performance as it does now, not making a copy of the statement.

  • C++

C++

#include <bits/stdc++.h>
using namespace std;
void swap(int &x, int &y) // function definition 

   int temp; // variable declaration 
   temp=x; 
   x=y; 
   y=temp; 
}
int main() 

   int a=9; // variable initialization 
   int b=10; // variable initialization 
   swap(a, b); // function calling 
   cout << "value of a is :" <<a<< endl; 
   cout << "value of b is :" <<b<< endl; 
   return 0; 
You can also try this code with Online C++ Compiler
Run Code

Output

value of a is : 10 
value of b is : 9 

References as Shortcuts

With the help of references, we can effortlessly access the nested data.

  • C++

C++

#include <bits/stdc++.h>
using namespace std;  
struct profile 

   int id; 
}; 
struct employee 

   profile p; 
}; 
int main() 

   employee e; 
   int &ref=e.p.id; 
   ref=34; 
   cout << e.p.id << endl; 
You can also try this code with Online C++ Compiler
Run Code

Output

34 

 

Try and compile with online c++ compiler.

Also check out this article - Pair in C++

References VS Pointers

References are often confused with pointers; however, three essential differences between references and pointers are −

  • You can not have NULL references. You always have to assume that a reference is connected to a useful storage piece.
  • When a reference is initialized to an object, it can’t be changed to refer to another object. Pointers may be pointed to another object at any time.
  • A reference has to be initialized when it’s far created. Pointers can be initialized at any time.

Must Read Lower Bound in C++

Limitations of References in C++

While references in C++ offer numerous benefits, they also come with some limitations:

  • Cannot Be Null
    Unlike pointers, references must always refer to a valid object or variable. This limitation means you cannot create a "null reference" or initialize a reference without a valid target.
  • Cannot Be Reassigned
    Once a reference is initialized to a variable, it cannot be changed to refer to another variable. This immutability can be restrictive in scenarios where reassignment might be beneficial.
  • Must Be Initialized at Declaration
    References must be initialized when they are declared. You cannot declare a reference and initialize it later, which can limit flexibility in some contexts.
  • No "Reference Arithmetic"
    Unlike pointers, references do not support arithmetic operations, such as incrementing or decrementing, which limits their use in certain situations (like traversing arrays).
  • Less Explicit Control Over Memory
    References provide less explicit control over memory than pointers. In some cases, this can make memory management and debugging more challenging, particularly in complex data structures.

Advantages of Using References in C++

Despite their limitations, references are a powerful feature in C++ and offer several key advantages:

  • Improved Code Readability
    References make code more readable and expressive because they resemble regular variables rather than memory addresses, as with pointers. This makes code easier to understand, especially for beginners.
  • Efficient Memory Usage
    References allow you to pass variables, especially large objects, without making copies, reducing memory usage and improving performance. This is particularly valuable in applications with memory constraints.
  • Enhanced Performance
    By eliminating the need for copies, references allow faster execution of programs, especially when handling large data structures or passing objects in functions.
  • Safer than Pointers
    References are generally safer than pointers because they must always be initialized to a valid target, reducing the risk of null pointer dereferences and other memory-related issues.
  • Support for Const Correctness
    Const references allow read-only access to objects, ensuring data integrity and signaling the function’s intent not to modify the original data. This makes the code more predictable and less prone to bugs.
  • Simplifies Complex Data Handling
    References are especially useful in complex applications where managing large data structures or objects can be challenging. They enable efficient, direct access to data without unnecessary duplication.

Frequently Asked Questions

What is the reference variable in C++?

A reference variable in C++ is an alias for another variable, meaning it refers directly to the original variable and cannot be changed to refer to another.

What does "by reference" mean in C++?

"By reference" in C++ means passing a variable to a function as a reference, allowing the function to modify the original variable’s value.

What is a reference type in C++?

A reference type in C++ is a type that refers to another variable, allowing indirect access to the original variable, such as a reference to an object or primitive.

Conclusion

We learned about the References and the differences between references and pointers also. We learned that references act as function formal parameters to support a pass-by way of reference. In a reference variable is passed into a function, the function works on the unique copy (in place of a clone copy in skip-by means of fee). Changes inside the function are reflected outdoor the function. After reading the theory, it’s time to head over to our practice platform Code360 to practice top problems on every topic, interview experiences, and many more. 

Recommended Readings: 

To learn more about Data Structures and Algorithms, you can enroll in our DSA in C++ Course.

Live masterclass