Monday, 16 March 2015

References in C++ with examples

References in C++ with examples:

In C++ the reference is nothing but the pointer that is automatically dereferenced.
The areas that references used as shown below.
1. Function argument lists.
2. Function return values.

int igVal;

int& iGRef = igVal;  // When a reference is created, it must be initialized to a live object.

const int& iCRef = 10;

Here is the example code that helps us to understand the references:
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <cstring>

using namespace std;

int main ()
  int iVal = 0; 
  int& iRef = iVal; 
  cout << "iVal = " << iVal << ", iRef = " << iRef << endl;
  cout << "iVal = " << iVal << ", iRef = " << iRef << endl;
  getchar ();
  return 0;

The output of the above program is
iVal = 0, iRef = 0

iVal = 1, iRef = 1

In line const int& iCRef = 12 the compiler allocates a piece of storage, initializes it with the value 10, and ties the reference to that piece of storage.
Thus, if you write lines like int iVal = 0 and int& iRef = iVal, then incrementing iRef is actually incrementing iVal, as is shown in main( ). Again, the easiest way to think about a reference is as a fancy pointer.

There are certain rules when using references:

1. A reference must be initialized when it is created.
2. Once a reference is initialized to an object, it cannot be changed to refer to another object.
3. You cannot have NULL references. You must always be able to assume that a reference is connected to a legitimate piece of storage.

No comments: