A reference variable is an alternative name for an existing variable. Instead of creating a new copy, references allow direct interaction with the original data.
Declaring a Reference
A reference is created using the &
operator, linking it to an existing variable.
Example: Creating a Reference
string bike = "Harley-Davidson"; // Original variable string &brand = bike; // Reference to bike
Now, both bike and brand refer to the same memory location.
Accessing a Reference
References behave identically to the original variable.
Example: Using a Reference
#include <iostream> using namespace std; int main() { string bike = "Harley-Davidson"; string &brand = bike; cout << bike << "\n"; // Outputs Harley-Davidson cout << brand << "\n"; // Outputs Harley-Davidson return 0; }
Both variables point to the same data, meaning changes made to one affect the other.
Why Use References?
References allow:
- Efficient variable management without unnecessary copying.
- Direct access to modify the original variable.
- Clean syntax for handling data in functions.