Creating References in C++
A reference in C++ is an alias for another variable. Once a reference is assigned to a variable, it cannot refer to another variable, and any operations on the reference directly affect the original variable.
Syntax of Creating a Reference
data_type &reference_name = variable_name;
Example: Creating a Reference
#include <iostream>
int main() {
int age = 30;
int &ref_age = age;
ref_age = 35;
std::cout << "Age: " << age << std::endl; // Output: 35
return 0;
}
Explanation: ref_age
is a reference to age
. Changing ref_age
updates age
because they refer to the same memory location.
Key Takeaways
- References are aliases for other variables and cannot be changed after initialization.
- They allow for efficient data manipulation without copying values.
- Useful in functions for passing variables by reference.