To see the basic idea, read the three pages [here].
#include <iostream.h> main() { int *A; A = new int[10]; // allocate array of 10 integers and point A to it if (! A) { cerr << "Out of memory!\n" << endl; exit(1); } for (int i = 0; i < 10; ++i) A[i] = i; int &B = A[3]; B = 999; for (int i = 0; i < 10; ++i) cout << "A[" << i << "] = " << A[i] << endl; delete[] A; }
Save this program as "tmp.cc", compile with "g++ -o tmp tmp.cc" and run the program. The output should be
A[0] = 0 A[1] = 1 A[2] = 2 A[3] = 999 A[4] = 4 A[5] = 5 A[6] = 6 A[7] = 7 A[8] = 8 A[9] = 9
// tmp2.cc #include <iostream.h> int & max_ref(int &a, int &b) { if (a > b) return a; else return b; } main() { int x = 3, y = 4; max_ref(x,y) = 999; cout << "x = " << x << ", y = " << y << endl; }
Returning a reference is especially useful when implementing an array class, when you want to be able to do something like:
#include "Array.h" main() { Array<int> A; A[3] = 10; }
To implement operator[] for the Array class so that A[3] can be assigned to as in this example, the operator[] member function will have to return a reference.
When you use a function to return a reference, make sure that the reference you return is still valid outside the function. For example, the following routine returns a reference to a variable that ceases to be defined outside the scope of the function. This can get you into all kinds of trouble:
// tmp3.cc #include <iostream.h> int & wrong() { int a = 1; return a; } main() { wrong() = 10; // this causes "10" to be written into a deallocated memory cell cout << wrong() << endl; // this prints the contents of a deallocated memory cell }
The compiler will compile it, but may warn you about the problem:
% make -k tmp3 g++ tmp3.cc -o tmp3 tmp3.cc: In function `int& wrong()': tmp3.cc:6: warning: reference to local variable `a' returned
and running the program will give you unpredictable results. Note that the exact same issue occurs with pointers to variables. For more information about this issue, see the CPlusPlusDocs page for information about variable scoping.