In C++, a reference is established using the ampersand (&) symbol. A reference variable in C++ serves as an alternative name for a pre-existing variable, providing a means to access the identical memory location under a different identifier. It is important to note that once a reference is initialized to a specific variable, it cannot be altered to point to a different variable.
The memory location of a different variable is held in a pointer, allowing indirect retrieval through dereferencing. Pointers that are reassigned have the flexibility to point to different memory addresses, a capability not shared by references.
Therefore, references offer a more straightforward and secure option compared to pointers for aliasing variables. This helps avoid the intricacies of pointer arithmetic while maintaining efficiency in data manipulation.
Syntax
It has the following syntax:
Type &referenceName = existingVariable;
Where,
- Type: It defines the reference's data type, which should be coincide with the type of the variable that is referenced.
- & (Ampersand): It shows that referenceName is a reference.
- referenceName: It is the name of the reference, which serves as an alias for the existing variable .
- = (Assignment Operator): It is commonly utilized to bind the reference to an already declared variable.
- existingVariable: It is the variable being referenced. It will works as an alternative name for this variable.
C++ Simple Reference Example:
Let's examine a C++ example of reference in C+.
Example
#include <iostream>
using namespace std;
int main()
{
int number = 25;
// Declare an integer variable
int &ref = number;
// Create a reference to 'number'
cout << "Original Value: " << number << endl;
cout << "Reference Value: " << ref << endl;
// Modifying the reference affects the original variable
ref = 50;
cout << "Modified Value: " << number << endl;
cout << "Modified Reference: " << ref << endl;
return 0;
}
Output:
Original Value: 25
Reference Value: 25
Modified Value: 50
Modified Reference: 50
Explanation:
This C++ code serves as an illustration of utilizing references. Initially, an integer variable named number is defined with an initial value of 25. Subsequently, a reference named ref is established, functioning as an alias for the number and pointing to the same memory address.
When the software outputs both numeral and reference, they exhibit identical values. Subsequently adjusting the reference to 50 directly results in the numeral being updated too, confirming that a reference functions as an alias for a preexisting variable. Subsequent to this, the software displays the altered values, demonstrating that both the numeral and reference presently contain the value 50.
Applications
Numerous uses of the pointers in C++ include:
1. Passing Argument by Reference:
The ampersand (&) operator is frequently used in C++ to pass arguments to functions by reference. Rather than dealing with a duplicate, it allows the function to alter the variable that was provided. This method is beneficial for altering the initial variable without the need to return a value. Additionally, it enhances efficiency when managing extensive data structures by preventing redundant duplications.
C++ Passing Argument by Reference Example:
Let's examine a C++ example of Passing Argument by Reference:
Example
#include <iostream>
// Function declaration
void swapValues(int& num1, int& num2);
int main()
{
int firstNum, secondNum;
// Taking input
std::cout << "Enter the first number: ";
std::cin >> firstNum;
std::cout << "Enter the second number: ";
std::cin >> secondNum;
//values before swapping
std::cout << "\nBefore swapping: First Number = " << firstNum << ", Second Number = " << secondNum << "\n";
// It calls the functions to swap
swapValues(firstNum, secondNum);
//values after swapping
std::cout << "After swapping: First Number = " << firstNum << ", Second Number = " << secondNum << "\n";
return 0;
}
// Function definition
void swapValues(int& num1, int& num2)
{
num1 = num1 + num2; // Step 1: Adding the both numbers
num2 = num1 - num2; // Step 2: Subtracting num2 from updated num1
num1 = num1 - num2; // Step 3: Subtracting updated num2 from updated num1
}
Output:
Enter the first number: 35
Enter the second number: 45
Before swapping: First Number = 35, Second Number = 45
After swapping: First Number = 45, Second Number = 35
Explanation:
In this instance, we exchange the positions of two numbers and make use of call-by-reference instead of employing a temporary variable. The swapValues function accepts two numbers as references from the user, allowing for direct alteration of the original values.
Within the function, mathematical calculations are employed to interchange the numbers by initially performing addition and subsequently subtraction to retrieve the original numbers in their exchanged locations. Ultimately, the revised values are showcased, indicating a successful swap operation.
2. Returning References from C++ Functions:
In C++, functions have the capability to return references to variables, allowing for efficient manipulation of extensive data structures and preventing redundancy. This technique is particularly beneficial for enhancing performance and facilitating alterations to a variable within a function.
Example:
Let's examine a C++ example showcasing the return of function references in C++.
Example
#include <iostream>
int& modifyValue(int& num)
{
num *= 2;
// it doubles the value
return num;
}
int main() //main function
{
int userInput;
std::cout << "Enter a number: "; //user input
std::cin >> userInput;
int& result = modifyValue(userInput);
std::cout << "Modified value: " << result << std::endl; //print output
return 0;
}
Output:
Enter a number: 4
Modified value: 8
Explanation:
This C++ code demonstrates the process of altering a variable by obtaining a reference from a function. The modifyValue function takes an integer reference as input, doubles its original value, and then provides a reference to the updated variable.
When a numeric value is provided by the user in the main function, the modifyValue function accepts it and performs an in-place update. The changes applied directly affect the original variable due to the function returning a reference, which helps prevent redundant copies from being generated.
3. Modifying Data in Range-Based Loops:
In a range-based loop, we can employ a reference (&) to modify the original elements within a container. This technique proves advantageous especially when working with extensive datasets as it reduces redundancy and enhances efficiency.
Example:
Let's examine a C++ example of Altering Data in Range-Based Loops.
Example
#include <iostream>
#include <string>
int main() //main function
{
std::string text;
std::cout << "Enter a word: ";
std::cin >> text;
for (char& ch : text)
{
ch = ch + 1;
// Incrementing each character
}
std::cout << "Modified text: " << text << std::endl; //print output
return 0;
}
Output:
Enter a word: Hello
Modified text: Ifmmp
Explanation:
In this instance, we employ a range-based for loop to alter every character in a word inputted by the user. The loop progresses through the letters sequentially (e.g., "a" transforms into "b") by traversing each character in the string by reference, incrementing its ASCII value by 1.
Advantages of Using References:
Several advantages of References in C++ are as follows:
- Safer than Pointers: References must be initialized that helps to reduce the risk of wild references.
- Simplified Syntax: References are simpler to use because they don't require the dereferencing operator (*) to access values.
- Direct Access: The arrow (->) operator needed for pointers can be replaced with the dot (.) operator to access object members.
Disadvantages of References in C++:
Several disadvantages of References in C++ are as follows:
- Immutable Binding: It cannot be reassigned to another object after they have been formed.
- Cannot Be Null: References must always be valid and cannot be NULL.
- Mandatory Initialization: References must be initialized at the time of declaration.
- Not Appropriate for Some Data Structures: References cannot be utilized to create dynamic data structures, such as linked lists or trees.
C++ References MCQS:
- Which of the following option is true about references in C++?
- They can be reassigned to another variable.
- They should always be initialized when declared.
- They can be NULL.
- They require a dereferencing operator (*) to access the value.
- What happens if a reference is not initialized at the time of declaration in C++?
- It causes a compilation error.
- It is automatically assigned NULL.
- It is assigned a garbage value.
- It behaves like a pointer.
(a) It results in a compilation error
- Which operator is employed when defining a reference in C++?
- What is the main advantage of using references over pointers in C++?
- References can be reassigned.
- They provide safer and easier access to variables.
- References support NULL values.
- They require explicit memory allocation.
- Can a function return a reference in C++?
- Yes, it allows changes of the original variable.
- No, functions may return only pointers.
- Yes, but it creates a new copy of the variable.
- No, returning a reference results in an error.
(a) Indeed, it permits modifications to the initial variable.