Group H
Group H
References
References are a powerful feature that allows us to create aliases or alternate names for existing
variables.
When we declare a references, we are essentially creating another name for existing object, this
reference then acts as a proxy for original object allowing us to access and manipulate its values
using different name.
Types of references
1.Lvalue
Refers to a named variable. It’s declared using the & operator. It behaves syntactically .
Example:
#include <iostream>
num++;
int main() {
int x = 5;
increment(x);
return 0;
}
Output:
Before x= 5
After x= 6
2. Rvalue
Refers to a temporary object. Its declared using the && operator. Are commonly used in move
semantics and perfect forwarding They can be universal reference, which can bind both R-values
and l-value.
Example:
#include<iostream>
#include<utility>
Void processValue(int&& num) {
Std::cout << “Processing rvalue:” << num << std::endl;
}
int main(){
int x = 5;
processValue(10);
processValue(std::move(x));
return 0;
}
Output:
Processing R-value: 10
Processing r-value:5
3.const references
Are references that provide read only access to the referred object.
Are often used as a function parameter to avoid making unnecessary copies and to express the
intention of not modifying the past object.
Example:
#include<iostream>
Void printValue(const int& num){
Std::cout<<”The value is:”<<num << std::endl;
}
int main(){
int x = 5;
const int& ref = x;
x = 10;
printValue(ref);
return 0;
}
Output:
The value is:10
Applications of references
1.Modifying passed parameters:
References are often used in function parameter passing to avoid unnecessary object copying.
When a function receives a reference to an object as a parameter, it can directly access and
modify the original object rather than creating a copy.
Example:
#include < iostream>
Void modifyParameter(int& num){
Num *=2;
}
Int main(){
int value = 5;
std::cout<< “Before modification: value”<<value<< std::endl;
modifyParameter(value);
std::cout << “After modification: value =”<< value << std::endl;
return 0;
}
Output:
Before modification: =10
After modification: = 5
3.Range-based loops:
References are often used in range-based loops to directly access and modify elements of a
container.
Example:
#include <iostream>
#include <vector>
int main(){
std::cout<< “Original numbers:”;
for(const int& num : numbers){
std::cout << num << “”;
}
Std::cout<< std::endl;
Std::cout << “Modified numbers:’;
for(int& num : numbers){
num* = 2;
std::cout << num << std::endl;
return 0;
}
Output:
Original numbers = 1,2,3,4,5
Modified numbers= 2,4,6,8,10