Download   Online Shop   Red Hat Network
Home  |  Products & Services  |  Support  |  Training  |  Partners  |  Documentation   
Red Hat Documentation

C++ Programming HOW-TO: Pointers are problems Next Previous Contents

5. Pointers are problems

Pointers are not required for general purpose programming. In modern languages like Java there is no support for pointers!! Pointers make the programs messy and programs using pointers are very hard to read.

Avoid using pointers as much as possible and use references. Pointers are really a great pain. It is possible to write a application without using pointers.

A reference is an alias; when you create a reference, you initialize it with the name of another object, the target. From the moment on, the reference acts as an alternative name of the target, and anything you do to the reference is really done to the target.

Syntax of References: Declare a reference by writing the type, followed by the reference operator (&), followed by the reference name. References MUST be initialized at the time of creation. For example -


        int             weight;
        int     & rweight = weight;
        DOG             aa;
        DOG & rDogRef = aa;

Do's of references -

  • Do use references to create an alias to an object
  • Do initialize all references
  • Do use references for high efficiency and performance of program.
  • Do use const to protect references and pointers whenever possible.

Do not's of references -

  • IMPORTANT: Don't use references to NULL objects !!!!
  • Don't confuse the address of operator & with reference operator !! The references are used in the declarations section (see Syntax of References above).
  • Don't try to reassign a reference
  • Don't use pointers if references will work
  • Don't return a reference to a local object
  • Don't pass by reference if the item referred to may go out of scope


Next Previous Contents

 

 
 
Search for:  on    Powered by Google
Products & Services   :   Download   :   Support   :   Training   :   Partners & Programs
© 2000 Red Hat, Inc. All right reserved.       About Red Hat   :   Legal statement   :   Privacy statement   :   Y2K statement   :   Contact Red Hat