The Wayback Machine - https://web.archive.org/web/20240830015118/https://www.geeksforgeeks.org/references-in-cpp/
Open In App

References in C++

Last Updated : 16 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

When a variable is declared as a reference, it becomes an alternative name for an existing variable. A variable can be declared as a reference by putting ‘&’ in the declaration. 

Also, we can define a reference variable as a type of variable that can act as a reference to another variable. ‘&’ is used for signifying the address of a variable or any memory. Variables associated with reference variables can be accessed either by its name or by the reference variable associated with it.

Prerequisite: Pointers in C++

Syntax:

data_type &ref = variable;

Example:

C++
// C++ Program to demonstrate 
// use of references
#include <iostream>
using namespace std;

int main()
{
    int x = 10;

    // ref is a reference to x.
    int& ref = x;

    // Value of x is now changed to 20
    ref = 20;
    cout << "x = " << x << '\n';

    // Value of x is now changed to 30
    x = 30;
    cout << "ref = " << ref << '\n';

    return 0;
}

Output: 

x = 20
ref = 30

Applications of Reference in C++

There are multiple applications for references in C++, a few of them are mentioned below:

  1. Modify the passed parameters in a function
  2. Avoiding a copy of large structures
  3. In For Each Loop to modify all objects
  4. For Each Loop to avoid the copy of objects

1. Modify the passed parameters in a function: 

If a function receives a reference to a variable, it can modify the value of the variable. For example, the following program variables are swapped using references. 

Example:

C++
// C++ Program to demonstrate
// Passing of references as parameters
#include <iostream>
using namespace std;

// Function having parameters as
// references
void swap(int& first, int& second)
{
    int temp = first;
    first = second;
    second = temp;
}

// Driver function
int main()
{
    // Variables declared
    int a = 2, b = 3;

    // function called
    swap(a, b);

    // changes can be seen
    // printing both variables
    cout << a << " " << b;
    return 0;
}

Output
3 2

 2. Avoiding a copy of large structures: 

Imagine a function that has to receive a large object. If we pass it without reference, a new copy of it is created which causes a waste of CPU time and memory. We can use references to avoid this. 

Example:

struct Student {
    string name;
    string address;
    int rollNo;
}

// If we remove & in below function, a new
// copy of the student object is created. 
// We use const to avoid accidental updates
// in the function as the purpose of the function
// is to print s only.
void print(const Student &s)
{
    cout << s.name << "  " << s.address << "  " << s.rollNo
         << '\n';
}

 3. In For Each Loop to modify all objects:

 We can use references for each loop to modify all elements.

Example:

C++
// C++ Program for changing the
// values of elements while traversing
// using references
#include <iostream>
#include <vector>

using namespace std;

// Driver code
int main()
{
    vector<int> vect{ 10, 20, 30, 40 };

    // We can modify elements if we
    // use reference
    for (int& x : vect) {
        x = x + 5;
    }

    // Printing elements
    for (int x : vect) {
        cout << x << " ";
    }
    cout << '\n';

    return 0;
}

Output
15 25 35 45 

 4. For Each Loop to avoid the copy of objects: 

We can use references in each loop to avoid a copy of individual objects when objects are large.  

Example:

C++
// C++ Program to use references
// For Each Loop to avoid the
// copy of objects
#include <iostream>
#include <vector>

using namespace std;

// Driver code
int main()
{
    // Declaring vector
    vector<string> vect{ "geeksforgeeks practice",
                         "geeksforgeeks write",
                         "geeksforgeeks ide" };

    // We avoid copy of the whole string
    // object by using reference.
    for (const auto& x : vect) {
        cout << x << '\n';
    }

    return 0;
}

Output
geeksforgeeks practice
geeksforgeeks write
geeksforgeeks ide

References vs Pointers

Both references and pointers can be used to change the local variables of one function inside another function. Both of them can also be used to save copying of big objects when passed as arguments to functions or returned from functions, to get efficiency gain. Despite the above similarities, there are the following differences between references and pointers.

1. A pointer can be declared as void but a reference can never be void For example

int a = 10;
void* aa = &a; // it is valid
void& ar = a;  // it is not valid

2. The pointer variable has n-levels/multiple levels of indirection i.e. single-pointer, double-pointer, triple-pointer. Whereas, the reference variable has only one/single level of indirection. The following code reveals the mentioned points:  

3. Reference variables cannot be updated.

4. Reference variable is an internal pointer.

5. Declaration of a Reference variable is preceded with the ‘&’ symbol ( but do not read it as “address of”).

Example:

C++
// C++ Program to demonstrate
// references and pointers
#include <iostream>
using namespace std;

// Driver Code
int main()
{
    // simple or ordinary variable.
    int i = 10;

    // single pointer
    int* p = &i;

    // double pointer
    int** pt = &p;

    // triple pointer
    int*** ptr = &pt;

    // All the above pointers differ in the value they store
    // or point to.
    cout << "i = " << i << "\t"
         << "p = " << p << "\t"
         << "pt = " << pt << "\t"
         << "ptr = " << ptr << '\n';

    // simple or ordinary variable
    int a = 5;
    int& S = a;
    int& S0 = S;
    int& S1 = S0;

    // All the references do not differ in their
    // values as they all refer to the same variable.
    cout << "a = " << a << "\t"
         << "S = " << S << "\t"
         << "S0 = " << S0 << "\t"
         << "S1 = " << S1 << '\n';

    return 0;
}

Output
i = 10    p = 0x7ffecfe7c07c    pt = 0x7ffecfe7c080    ptr = 0x7ffecfe7c088
a = 5    S = 5    S0 = 5    S1 = 5

Limitations of References

  1. Once a reference is created, it cannot be later made to reference another object; it cannot be reset. This is often done with pointers. 
  2. References cannot be NULL. Pointers are often made NULL to indicate that they are not pointing to any valid thing. 
  3. A reference must be initialized when declared. There is no such restriction with pointers.

Due to the above limitations, references in C++ cannot be used for implementing data structures like Linked List, Tree, etc. In Java, references don’t have the above restrictions and can be used to implement all data structures. References being more powerful in Java is the main reason Java doesn’t need pointers.

Advantages of using References

  1. Safer: Since references must be initialized, wild references like wild pointers are unlikely to exist. It is still possible to have references that don’t refer to a valid location (See questions 5 and 6 in the below exercise) 
  2. Easier to use: References don’t need a dereferencing operator to access the value. They can be used like normal variables. The ‘&’ operator is needed only at the time of declaration. Also, members of an object reference can be accessed with the dot operator (‘.’), unlike pointers where the arrow operator (->) is needed to access members.

Together with the above reasons, there are a few places like the copy constructor argument where a pointer cannot be used. Reference must be used to pass the argument in the copy constructor. Similarly, references must be used for overloading some operators like ++.

Exercise with Answers

Question 1 :

C++
#include <iostream>
using namespace std;

int& fun()
{
    static int x = 10;
    return x;
}

int main()
{
    fun() = 30;
    cout << fun();
    return 0;
}

Output
30

Question 2 

C++
#include <iostream>
using namespace std;

int fun(int& x) { return x; }

int main()
{
    cout << fun(10);
    return 0;
}

Output:

./3337ee98-ae6e-4792-8128-7c879288221f.cpp: In function 'int main()':
./3337ee98-ae6e-4792-8128-7c879288221f.cpp:8:19: error: invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int'
     cout << fun(10);
                   ^
./3337ee98-ae6e-4792-8128-7c879288221f.cpp:4:5: note: in passing argument 1 of 'int fun(int&)'
 int fun(int& x) { return x; }

Question 3 

C++
#include <iostream>
using namespace std;

void swap(char*& str1, char*& str2)
{
    char* temp = str1;
    str1 = str2;
    str2 = temp;
}

int main()
{
    char* str1 = "GEEKS";
    char* str2 = "FOR GEEKS";
    swap(str1, str2);
    cout << "str1 is " << str1 << '\n';
    cout << "str2 is " << str2 << '\n';
    return 0;
}

Output
str1 is FOR GEEKS
str2 is GEEKS

Question 4 

C++
#include <iostream>
using namespace std;

int main()
{
    int x = 10;
    int* ptr = &x;
    int&* ptr1 = ptr;
}

Output:

./18074365-ebdc-4b13-81f2-cfc42bb4b035.cpp: In function 'int main()':
./18074365-ebdc-4b13-81f2-cfc42bb4b035.cpp:8:11: error: cannot declare pointer to 'int&'
     int&* ptr1 = ptr;

Question 5 

C++
#include <iostream>
using namespace std;

int main()
{
    int* ptr = NULL;
    int& ref = *ptr;
    cout << ref << '\n';
}

Output:

timeout: the monitored command dumped core
/bin/bash: line 1:    34 Segmentation fault     
timeout 15s ./372da97e-346c-4594-990f-14edda1f5021 < 372da97e-346c-4594-990f-14edda1f5021.in

Question 6 

C++
#include <iostream>
using namespace std;

int& fun()
{
    int x = 10;
    return x;
}

int main()
{
    fun() = 30;
    cout << fun();
    return 0;
}

Output:

Segmentation Fault (SIGSEGV)
timeout: the monitored command dumped core
/bin/bash: line 1: 31 Segmentation fault

 



Previous Article
Next Article

Similar Reads

lvalues references and rvalues references in C++ with Examples
Prerequisites: lvalue and rvalue in C++, References in C++“l-value” refers to a memory location that identifies an object. "r-value” refers to the data value that is stored at some address in memory. References in C++ are nothing but the alternative to the already existing variable. They are declared using the '&amp;' before the name of the variabl
4 min read
Can References Refer to Invalid Location in C++?
Reference Variables: You can create a second name for a variable in C++, which you can use to read or edit the original data contained in that variable. While this may not sound appealing at first, declaring a reference and assigning it a variable allows you to treat the reference as if it were the original variable for the purposes of accessing an
2 min read
Default Assignment Operator and References in C++
We have discussed assignment operator overloading for dynamically allocated resources here. In this article, we discussed that when we don't write our own assignment operator, the compiler creates an assignment operator itself that does shallow copy and thus causes problems. The difference between shallow copy and deep copy becomes visible when the
2 min read
Pointers vs References in C++
Prerequisite: Pointers, References C and C++ support pointers, which is different from most other programming languages such as Java, Python, Ruby, Perl and PHP as they only support references. But interestingly, C++, along with pointers, also supports references. On the surface, both references and pointers are very similar as both are used to hav
5 min read
Pointers and References in C++
In C++ pointers and references both are mechanisms used to deal with memory, memory address, and data in a program. Pointers are used to store the memory address of another variable whereas references are used to create an alias for an already existing variable. Pointers in C++ Pointers in C++ are a symbolic representation of addresses. They enable
5 min read
Why Can't I Make a Vector of References?
In C++, the Standard Template Library (STL) provides a robust and versatile collection of containers, with std::vector being one of the most commonly used. However, you may encounter an obstacle when trying to create a vector of references. In this article, we are going to look at why you cannot make a vector of references and some ways around it t
4 min read
C++ Programming Language
C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read
30 OOPs Interview Questions and Answers (2024)
Object-Oriented Programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
C++ Programming Examples
Writing C++ programs yourself is the best way to learn the C++ language. C++ programs are also asked in the interviews. This article covers the top practice problems for basic C++ programs on topics like control flow, patterns, and functions to complex ones like pointers, arrays, and strings. C++ Tutorial C++ Recent Articles Topics: Basic Programs
9 min read
C++ Interview Questions and Answers (2024)
C++ - the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent in C++. It is utilized by top IT companies such as
15+ min read
Left Shift and Right Shift Operators in C/C++
In C/C++, left shift (&lt;&lt;) and right shift (&gt;&gt;) operators are binary bitwise operators that are used to shift the bits either left or right of the first operand by the number of positions specified by the second operand allowing efficient data manipulation. In this article, we will learn about the left shift and right shift operators. Le
6 min read
vector erase() and clear() in C++
Prerequisite: Vector in C++ Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::clear() The clear() function is used to remove all the elements of the vector container, thus making it size 0. Syntax
6 min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is &lt;string&gt;. The substring function takes two values pos and len as an argument
8 min read
Virtual Function in C++
A virtual function (also known as virtual methods) is a member function that is declared within a base class and is re-defined (overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the meth
6 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the
15+ min read
C++ Polymorphism
The word "polymorphism" means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. A real-life example of polymorphism is a person who at the same time can have different characteristics. A man at the same time is a father, a husband, and an employee. So the same person ex
7 min read
C++ Classes and Objects
In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. In this article, we will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program. What is a Class in C++?A class is a user-defined data type, which holds its own data members and member functions, w
9 min read
C++ Data Types
All variables use data type during declaration to restrict the type of data to be stored. Therefore, we can say that data types are used to tell the variables the type of data they can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared. Every data type
10 min read
Convert String to int in C++
Converting a string to int is one of the most frequently encountered tasks in C++. As both string and int are not in the same object hierarchy, we cannot perform implicit or explicit type casting as we can do in case of double to int or float to int conversion. Conversion is mostly done so that we can convert numbers that are stored as strings. Exa
8 min read
std::sort() in C++ STL
We have discussed qsort() in C. C++ STL provides a similar function sort that sorts a vector or array (items with random access) It generally takes two parameters, the first one being the point of the array/vector from where the sorting needs to begin and the second parameter being the length up to which we want the array/vector to get sorted. The
6 min read
Priority Queue in C++ Standard Template Library (STL)
A C++ priority queue is a type of container adapter, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue, and elements are in non-increasing or non-decreasing order (hence we can see that each element of the queue has a priority {fixed order}). In C++ STL, the top elemen
11 min read
Vector in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inse
10 min read
Map in C++ Standard Template Library (STL)
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the &lt;map&gt; header file. Basic std::map Member FunctionsSome basic functions associated with std::
8 min read
The C++ Standard Template Library (STL)
The Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures and functions such as lists, stacks, arrays, etc. It is a library of container classes, algorithms, and iterators. It is a generalized library and so, its components are parameterized. Working knowledge of template classes is a prerequ
5 min read
Object Oriented Programming in C++
Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data
9 min read
Operator Overloading in C++
in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning. In this article, we will further discuss about operator overloading in C++ with examples and see which operators we can or cannot overload in C++. C++ Operator OverloadingC++ has
8 min read
Templates in C++ with Examples
A template is a simple yet very powerful tool in C++. The simple idea is to pass the data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need to sort() for different data types. Rather than writing and maintaining multiple codes, we can write one sort() and pass the dat
10 min read
Friend Class and Function in C++
A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private and protected members of other classes. For example, a LinkedList class may be allowed to access private members of Node. We can declare a friend class in C++ by using the
6 min read
Constructors in C++
Constructor in C++ is a special method that is invoked automatically at the time an object of a class is created. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. It constructs the values i.e. provides data for the object which is why it is known as a constructor
7 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The &amp; (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
Article Tags :
Practice Tags :