1. Home
C++ Tutorial

Explore C++ Tutorials: Exploring the World of C++ Programming

Discover comprehensive C++ tutorials designed for beginners and advanced programmers alike. Enhance your coding skills with step-by-step guides and practical examples.

  • 77 Lessons
  • 15 Hours
right-top-arrow
4

Understanding Reference Variable in C++: Definition and Usage

Updated on 18/09/2024420 Views

The idea of a reference variable in C++ caught my attention because it is straightforward yet powerful. To put it simply, a reference variable acts like an alias for another variable. This means that we can give different names to the same piece of memory and use those names interchangeably. So, when you modify the value through one name, it will also change if you check from the other name.

Let’s see what exactly does this mean and imply. Let’s start by first seeing how we define a reference variable in C++. Then, we will go on to elaborately explain reference variable in C++.

Define Reference Variable in C++

In C++, you declare a reference variable by putting an ampersand (&) between the variable type and its name. Like this: int& ref = original; This line makes a reference variable called ref that points to an integer variable original. The important characteristic of a reference variable is that any action taken on this reference is actually done on the first variable it aliases with.

How to initialize reference variable in C++

A reference variable, when declared, must be given an initial assignment. Once this is done, it cannot be rebound to point to another variable. You can provide an initial value in the following manner:

int x = 5;int& ref = x;

In this example, ref is a reference to x. Any changes made to ref will affect x because they refer to the same memory location.

Reference Variable in C++ example

To help you understand better, let's look at a simple example:

Example: 

Example of reference variable in C++

Output: 

Output for the reference variable example

Code: 

#include <iostream>

using namespace std;

int main() {

    int a = 10;

    int& ref = a;

    cout << "a = " << a << endl;

    cout << "ref = " << ref << endl;

    ref = 20;  // Modifying the reference affects the original variable

    cout << "After modifying ref:" << endl;

    cout << "a = " << a << endl;

    cout << "ref = " << ref << endl;

    return 0;

}

Reference variable in C++ program

Consider the following program that uses reference variables to swap two numbers:

Example: 

Swap program using reference variable in C++

Output: 

Output for the swap program using reference variable in C++

Code: 

#include <iostream>

using namespace std;

void swap(int& x, int& y) {

int temp = x;

x = y;

y = temp;

}

int main() {

int a = 10, b = 20;

cout << "Before swap: a = " << a << ", b = " << b << endl;

swap(a, b);

cout << "After swap: a = " << a << ", b = " << b << endl;

return 0;

}

Now, the swap function is modified. It uses reference variables to exchange values of a and b without involving pointers.

Now, let’s try to understand what is the use of reference variable in C++.

What is the Use of Reference Variable in C++

A reference variable in C++ is a very useful and adaptable tool. They can make your code more effective and understandable. You use reference variables for different purposes like:

1. Function arguments and return types:

(a) Modify actual parameters: I use passing parameters to functions by reference, this lets the functions change the real values of arguments without requiring pointers. It's easier to read and understand in comparison with using pointers.

Example: 

Program for modifying actual parameters using reference variable in C++

Output: 

Output for the program

Code:

void increment(int& num) {

num++;

}

int main() {

int a = 5;

increment(a);

std::cout << a << std::endl; // Outputs 6

return 0;

}

(b). Efficient data passing: While working with big data structures or objects (such as large vectors or types defined by users), it may not be efficient to pass them by value, meaning make a copy. When we pass through reference, it doesn't need to copy the whole data structure so we save both time and memory.

void processLargeVector(const std::vector<int>& vec) {

// Process the vector without copying it

}

(c). Using references for return types: To not copy complex structures, you can use references as return types. But, make sure the referenced object's life is longer than the reference's usage time.

int& getElement(std::vector<int>& vec, size_t index) {

return vec[index]; // Return a reference to the element

}

2. Efficiency in copying and assignment:

When dealing with user-defined types, each time an object is initiated from another object, a copy constructor is called. If I utilize reference variables instead, it can help me skip this overhead and make the initialization quicker and more effective.

class BigObject {

std::vector<int> largeData;

public:

BigObject(const BigObject& other) : largeData(other.largeData) {

std::cout << "Copy constructor called!" << std::endl;

}

// By using references, I avoid unnecessary copying

BigObject(const BigObject& other, bool avoidCopy) : largeData(other.largeData) {}

};

3. Operator overloading: 

(a). Natural syntax: References make it possible for certain operators to be overloaded, such as assignment, to behave like they do with fundamental types. This ability gives a user-defined type a more intuitive and natural syntax.

class Point {

public:

int x, y;

Point& operator+=(const Point& rhs) {

x += rhs.x;

y += rhs.y;

return *this;

}

};

(b). Chain assignments: The capability of chaining operations, such as a = b = c, is made possible by references because the assignment operator can give back a reference to the operand on the left side.

Point a, b, c;

a = b = c; // Chained assignment

4. Implementing data structure

Reference variables can be used in many ways to make different data structures. They are helpful for connecting nodes in linked lists, trees, graphs and other linked structures.

struct Node {

int value;

Node* next;

Node(int val) : value(val), next(nullptr) {}

};

void connectNodes(Node& a, Node& b) {

a.next = &b;

}

5. Easy aliasing: 

At times, I desire a shorter or more significant name for a component of a data structure or an extensive expression to enhance clarity or convenience. In this situation, references can assist in creating an alias.

std::pair<int, int> coordinates;

int& x = coordinates.first;

int& y = coordinates.second;

6. Range-based for loops

In range-based for loops, when I use reference variables, it lets me modify elements directly. This way is more brief and understandable compared to traditional for loops with indices.

std::vector<int> numbers {1, 2, 3, 4, 5};

for (int& num : numbers) {

num *= 2; // Double each number

}

If you want to understand reference variables more completely and enhance your abilities in programming, you could study some courses from upGrad. They have a full course that plans for making students into skilled software engineers, giving the necessary knowledge for using C++ features proficiently in real-time projects.

Reference Variables in C++ vs Pointers in C++

While reference variables and pointers in C++ share some similarities, there are fundamental differences:

  • Initialization: When declared, references must be initialized. Pointers, on the other hand, can be left uninstantiated until a later time.
  • Null Value: A reference can't be null, but a pointer is able to be null, not pointing at any object.
  • Reassignment: Once a reference is initialized, it cannot be changed to refer to another variable. On the other hand, you can reassign a pointer to point at different objects or variables.
  • Dereferencing Not Needed: To reach the value that a reference points to, there is no need for dereferencing like with pointers.

Here’s a difference table elaborating on these d differences between reference variables in C++ vs pointers in C++. 

Feature

References in C++

Pointers in C++

Initialization

Must be initialized at declaration. Cannot be null.

Can be initialized at any time. Can be null.

Reassignment

Cannot be reassigned to refer to a different variable.

Can be reassigned to point to different objects.

Syntax

Act like normal variables. No special syntax needed for accessing.

Require dereferencing (*) to access the object they point to.

Memory Address

Do not have their own memory address.

Have their own memory address. Can use & to access it.

Nullability

Cannot be null. Always refer to an initialized object.

Can be null, indicating they point to no object.

Flexibility

Less flexible but safer and easier to use.

More flexible but prone to errors like null dereferencing.

Pointer Arithmetic

Not applicable.

Can perform pointer arithmetic.

Use in Dynamic Memory

Not used for dynamic memory allocation directly.

Used with new and delete for dynamic memory management.

Function Parameters

Used to pass arguments by reference without copying.

Used to pass arguments by pointer, can be modified.

Memory Overhead

Generally none, but depends on compiler implementation.

Always occupy memory (size of a pointer).

Typical Use Cases

Function arguments, operator overloading, avoiding object slicing.

Dynamic memory, arrays, low-level system interaction.

So, although both references and pointers in C++ are powerful tools for working with variables and memory, they have different features that make them suitable for different tasks. References offer a safer and easier way to handle memory compared to pointers, especially when you wish to avoid the intricacies of pointer arithmetic along with null pointers risks. However, pointers still hold more power and flexibility in some situations – like low-level programming or dynamic memory handling – as well as handling arrays or other data structures where manipulation of memory addresses becomes necessary.

Concluding Remarks

Reference variables in C++ are a valuable yet simple way to refer to other variables. If you understand and use references correctly, your C++ code will be more efficient and easier to understand. Keep in mind that references are like any other tool; using them well is crucial for creating good software.

For people who want to learn more about C++ and other methods in software engineering, I suggest you check out the range of courses offered by upGrad. These courses are planned to assist you in increasing your career abilities.

FAQs

1. What is a reference variable in C++?

In C++, a reference variable is like another name for a different variable. It's an alternative way to access the same memory location.

2. How do you declare a reference variable in C++?

You can declare a reference in C++ by starting with an ampersand symbol & and then the variable name. For instance: int& ref = original;.

3. What is the difference between a pointer and a reference variable in C++?

The key differences are that a reference cannot be null, must be initialized when declared, and its initialization cannot be changed afterwards to refer to another object. On the other hand, a pointer can hold null, can be reassigned and requires dereferencing for accessing the value it points to.

4. What are the main uses of reference variables in C++?

They are utilized for parameter passing in functions, preventing object slicing in inheritance, managing operator overloading and to make complex data structures.

5. Can a reference variable refer to a constant value in C++?

No, a reference in C++ cannot be directly initialized to a constant value. Nonetheless, it is possible to have a reference to the constant such as const int& ref = someVariable;.

6. Can a reference variable refer to another reference variable in C++?

Certainly, it's possible for a reference variable to reference another reference. This subsequent reference could be pointing to the original variable or might even be another reference itself. In essence, all references are linked back to some primary variable.

7. Are reference variables in C++ always initialized?

Certainly, when we declare a reference variable, it must also be set to an initial value. This is necessary in C++ to guarantee that they always point towards a valid location.

8. Can a reference variable refer to a temporary object in C++?

A non-const reference can't be started with a temporary object. But, you can lengthen the life of a temporary object by using a const reference and it will exist until the end of its scope.

Kechit Goyal

Kechit Goyal

Team Player and a Leader with a demonstrated history of working in startups. Strong engineering professional with a Bachelor of Technology (BTech…Read More

Need Guidance? We're Here to Help!
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...