C++ interfaces a new kind of variable known as the reference variable. A reference variable provides an alias (alternative name) for a previously defined variable.
A reference is another name, or alias, for an object that already exists. Defining a reference does not occupy additional memory.
Any operations defined for the reference are performed with the object to which it refers. References are particularly useful as parameters and return values of functions.
Datatype & reference–name = variable name;
Example: if we make the variable sum a reference to the variable total, then sum and total can be used interchangeably to represent the variable.
float total=1500; float &sum=total;
Here, sum is the alternative name for variables total, both the variables refer to the same data object in the memory. A reference variable must be initialized at the time of declaration. Note that C++ assigns additional meaning to the symbol &. Here, & is not an address operator. The notation float & means reference to float.
int n; int &x=n; char &a=’\n’;
A reference must be initialized when it is declared, and cannot be modified subsequently. In other words, you cannot use the reference to address a different variable at a later stage.
A reference that addresses a constant object, must be a constant itself. It must be defined using the const keyword to avoid modifying the object by reference. However, it is conversely possible to use a reference to a constant to address a non-constant object.
int a; const int& cref = a;
The reference cref can be used for read-only access to the variable a, and is said to be a read-only identifier. A read-only identifier can be initialized by a constant, in contrast to a normal reference. Since the constant does not take up any memory space, the compiler creates a temporary object which is then referenced.
const double& pi = 3.1415927;
Since the constant does not take up any memory space, the compiler creates a temporary object which is then referenced.
You must log in to post a comment.