CPlusPlusDocs/References

Top | CPlusPlusDocs | recent changes | Preferences

Showing revision 8
A "reference" in C++ is a variable that refers to another variable. You can think of it as an alias.

To see the basic idea, read the three pages [here].

Assigning to a reference

Note that assigning to a reference changes the value of the variable to which the reference refers. To make sure you understand this, consider this program:
// tmp.cc
#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

Functions can return references

The second thing that I want you to understand is that a function can return a reference. For example:


// 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;

}

What do you think this will output? It should output "x = 3, y = 999".

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.

Be careful about the scope of the variable you 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.


Top | CPlusPlusDocs | recent changes | Preferences
This page is read-only | View other revisions | View current revision
Edited April 1, 2004 10:55 am by NealYoung (diff)
Search: