Cpp - Reference Defining References

Introduction

A reference is alias for an object that already exists.

Defining a reference does not occupy additional memory.

Any operations on the reference are performed with the object to which it refers.

References are particularly useful as parameters and return values of functions.

The ampersand character, &, is used to define a reference.

Given that T is a type, T& denotes a reference to T.

float x = 10.7; 
float& rx = x;   // or:  float &rx = x; 

rx is an alias for x.

Operations with rx, such as

--rx;// equivalent to  --x; 

will automatically affect the variable x.

The & character indicates a reference and is not related to the address operator &!

The address operator returns the address of an object.

If you apply this operator to a reference, it returns the address of the referenced object.

&rx    // Address of x, thus is equal to &x 

A reference must be initialized when it is declared, and cannot be modified subsequently.

You cannot use the reference to address a different variable.

Demo

// Demonstrates the definition and use of references. 
#include <iostream> 
#include <string> 
using namespace std; 

float x = 1.7F;        

int main() //from  w w w .j  a v  a2s  . co m
{ 
   float  &rx = x;      // Local reference to x 
   rx *= 2; 

   cout << "   x = " <<  x << endl    
        << "  rx = " << rx << endl;   

   const string str = "I am a constant string!"; 
   const string& text = str;  
   cout << text << endl;
   return 0; 
}

Result

Related Topic