A reference variable is an alias, meaning an already existing variable. If a reference variable is initialized, either the variable name or the reference name can be used to refer to the variable.
Most programmers confuse references with pointers, however, there are three major differences between references and pointers. they are listed below:
A reference must always be initialized once it is created, while Pointers can always be initialized at any time.
Pointers can be pointed to another object at any time and you cannot have Null references, while a Reference is initialized to an object, and cannot be changed to refer to another object.
Finally, you must always be able to assume that a reference is connected to a legitimate piece of storage that is unique to it.
Creating References in C++
To create a reference in the C++ program easily, use the following steps:
Firstly, you should think of a variable name as a label attached to the variable's location in memory.
Think of a reference as a second label attached to that memory location.
You can access the contents of the variable through either the original variable name or the reference. Take, for instance, suppose we have the following syntax:
Syntax:
int i = 17;
We can declare reference variables for i as follows.
int& s = i;
Read the ‘&’ in the declaration above as a reference.
Also, read the first declaration as "sis an integer reference initialized to i" and then read the second declaration as "v is a double reference initialized to d."
The example below makes use of references on int and double:
Example:
#include <iostream>
int main ()
{
// declare simple variables
int i;
double d;
// declare reference variables
int& s = i;
double& v = d;
i = 9;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << s << endl;
d = 99.7;
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << v << endl;
return 0;
}