C++ Programming Concepts

Learn C++ and get Object Oriented

C++ Programming Concepts made easy...

C++ Programming Concepts - Reference and Reference Operator

C++ Programming Concepts - Reference and Reference Operator

The C++ Programming Language allows a programmer to create a nick name or an alias to an existing variable. This alias is called a Reference - just another way to refer to the same variable - and thus it has to be initialized, it cannot be assigned a value. After all, once created, it must know which variable it is referring to, and it has to be a variable, it can't be NULL.

For creating a reference, we use the reference operator (&). The Reference Operator and the Address of Operator use the same Symbol - the compiler is able to distinguish between the two by context.

int i ; /* Integer variable i */
int *p = &i ; 

/* Pointer p pointing to variable i, or pointer variable p containing the address of location of variable i */

int& q = i ; /* An integer Reference referring to integer variable i.

A reference once initialized points to the same variable. Also, once you've initialized a reference, it can't be uninitialized. So the referenced variable is stuck with the Reference till either the variable or the reference is destroyed. (For automatic variables, the variable or the reference will be destroyed as soon as they go out of scope.)

Operations on References

When a value is assigned to the reference, the value is actually being assigned to the variable the reference is referring to. 

For e.g.,

q = 5 ;

would entail that now the value stored in variable i is 5. Similarly, any other modification made to the reference, by say, increment or decrement operators, will modify the variable.

 q++ ; // Value of i is 6 

When the reference is used in an expression, it basically means that you're simply using the variable it is referring to. So if the Reference is displayed, the value of the variable will be displayed; if the Reference is used in an arithmetic operation, it would be as if we are using the variable.
int k = q + 8 ; // Value of k would be, 8 + 6 = 14

Now, consider the code:

int m = 5 ;
i = m;
m = i ;
i++ ;

Since, m is a normal variable, assigning m to i simply means creating a copy of value of m into i. For the time being, m and i are containing same values. But once i is incremented, the variables m and i are no more containing the same values. m would be 5, and i would become 6.

It's important to understand that a reference is not a copy, it's the variable itself. Thus, after the above code, if q and i are displayed, both will display 6. They will display the same value always, because they are referring to the same memory location. References have many interesting and indispensable usages in C++ which would be discussed later.