C++ References
A reference variable is an alias, meaning it is another name for an already existing variable. Once a reference is initialized with a variable, either the reference name or the variable name can be used to refer to the variable.
C++ References vs Pointers
References are often confused with pointers, but there are three main differences between them:
There are no null references. A reference must be connected to a valid block of memory.
Once a reference is initialized to an object, it cannot be pointed to another object. A pointer can be pointed to another object at any time.
A reference must be initialized when it is created. A pointer can be initialized at any time.
Creating References in C++
Think of a variable name as a label attached to the variable's location in memory. You can consider a reference as a second label attached to that memory location. Thus, you can access the contents of the variable through the original variable name or the reference. For example:
int i = 17;
We can declare reference variables for i as follows:
int& r = i;
double& s = d;
In these declarations, the &
is read as reference. Therefore, the first declaration can be read as "r is an integer reference initialized to i," and the second declaration can be read as "s is a double reference initialized to d." The following example uses int and double references:
Example
#include <iostream>
using namespace std;
int main ()
{
// Declare simple variables
int i;
double d;
// Declare reference variables
int& r = i;
double& s = d;
i = 5;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << r << endl;
d = 11.7;
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << s << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Value of i : 5
Value of i reference : 5
Value of d : 11.7
Value of d reference : 11.7
References are commonly used in function parameter lists and function return values. The following are two important concepts related to C++ references that C++ programmers must understand:
Concept | Description |
---|---|
Passing Parameters by Reference | C++ supports passing references as parameters to functions, which is safer than passing regular parameters. |
Returning Values by Reference | References can be returned from C++ functions, just like other data types. |