1. Computing & Technology

Discuss in my forum

C++ Tutorial - Learn to use References

By , About.com Guide

More details of how Example 8_3 works
A reference variable that does not point to something is undefined and likely to deal your application a fatal (if not caught) exception.

Although technically a reference isn't quite the same as a pointer, if you are used to thinking in pointer terms then conceptually references are just easier to use pointers!

Remember it was stated that References must be initialized when created. In a class, you will get compile errors unless you initialize a reference from an initializer list. Why is this?

Unassigned References

Unattached references cannot exist. A declaration like
 map & m;
 
Where map is some known class is not allowed unless it is initialized and the only place to do this is in the initializer list of a constructor.

Example 8_4 on the next page shows an example of this taken from a game with a map and one or more armies that must be located on the map.

©2012 About.com. All rights reserved.

A part of The New York Times Company.