
Reference Variables
A reference variable provides an alias ( alternative name ) for a previously defined variable. When you declare a reference variable, you give it a value that you may not change for the life of the reference. The & operator identifies a reference variable as in the following example:
int m = 50 ;
int & n = m ;
n is the alternative name declared to represent the variable m. Both variables refer to the same data object in the memory. Now, the statements
cout << m ;
and
cout << n ;
both print the value 50. The statement
m = m + 20 ;
will change the value of both m and n to 70. Likewise, the assignment
n = 0 ;
will change the value of both the variables to zero.
A reference variable must be initialized at the time of declaration. Note that the initialization of a reference variable is completely different from assignment to it.
To prove that reference variables do not have separate existence in memory, if programmer takes the address of one, all she will get is the address of the variable for which it is an alias.
For example,
int main ( )
{
int m = 10 ;
int & n = m ;
cout << " Address of m " << &m << endl ;
cout << " Address of n " << &n << endl ;
return 0;
}
produced the following output ( on a particular machine )
Address of m 0xfff2
Address of n 0xfff2
Following is a list of things to remember when you deal with references:
- A reference is an alias for an actual variable.
- A reference must be initialized and cannot be changed.
- References works well with user-defined data types.
- You can pass references to functions.
- You can return references from functions.
- A function that returns a reference can appear on either side of an assignment.
- The only thing you can do to the reference variable itself is initialize it.