References in C++
Written by
A reference variable is an alias, which is, another name for an already existing variable.
But what is its significance? Its significance is that once a reference is initialized with a variable, either the variable name or the reference name may be used to refer to the variable.
References and Pointers:
References are often confused with pointers but the major differences between references and pointers are −
We cannot have NULL references. While the NULL pointers are possible and we have already learned about them in the previous chapters.
Once a reference is initialized to an object, it cannot be changed to refer to another object.
A reference must be initialized when it is created. Pointers can be initialized at any time.
Creating References in C++:
Let us think of an example here. Suppose there is a child whose full name is Anthony, and his nickname is Tony. Here Anthony and Tony are both different names but they both are used to refer to the same person. Same is the case for the variable names and the references as well.
For example, suppose we have the following example −
int i = 17;
We can declare reference variables for i as follows.
int &r = i;
Following example makes use of references on int and double −
#include <iostream.h>
int main () {
// declare simple variables
int i;
// declare reference variables
int &r = i;
i = 10;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << r << endl;
return 0;
}
When the above code is compiled together and executed, it produces the following result −
Value of i: 10
Value of i reference: 10
Here r is the reference of the integer variable i and both have the same values as they are just two different names that point to the same memory location.