1. Computing & Technology

Discuss in my forum

C++ Tutorial - Learn to use References

By , About.com Guide

1 of 7

How to Use References
A major difference between C and C++ (other than Objects and Classes!) is references.

A reference is like a const pointer to a variable. Assigning a reference is a bit like using a pointer but with & not * and you don't need to dereference. The difference is that you assign an address to a pointer but a variable to a reference variable.

The line below suggests that the value of a is copied into aref. But it is not, instead aref is a reference to the variable a. Once assigned, aref is the same as a. Any changes to aref are changes to a as example 8_1 shows.

 int & aref = a; 
 
 //ex8_1
 #include <stdio.h>
 #include "stdafx.h"
 
 int main()
 {
 	int a=9;
 	int & aref = a;
 	a++;
 cout << "The value of a is %i\n" << aref;
 	return 0;
 }
 
Things you should always remember about references.
  • A reference must always refer to something. NULLs are not allowed.
  • A reference must be initialized when it is created. An unassigned reference can not exist.
  • Once initialized, it cannot be changed to another variable.

What is the point of references?

For code like this not much. But in functions, references allow values to be passed by reference. In C, the big problem was that parameters to functions were copied in. To change a variable defined external to the function required pointers which made programming more complicated.

On the next page : Learn about reference parameters

©2012 About.com. All rights reserved.

A part of The New York Times Company.