Contents Up << >>

What is a reference?

An alias (an alternate name) for an object.

References are frequently used for pass-by-reference:

  	void swap(int& i, int& j)
	{
	  int tmp = i;
	  i = j;
	  j = tmp;
	}

	main()
	{
	  int x, y;
	  //...
	  swap(x,y);
	}
Here, i and j are aliases for main's x and y respectively. In other words, i is x -- not a pointer to x, not a copy of x, but x itself. Anything you do to i gets done to x, and vice versa.

Underneath it all, references are typically implemented by pointers. The effect is as if you used the C style pass-by-pointer, but the "&" is moved from the caller into the callee, and you eliminate all the "*"s.