References as an Alternative to Pointers

Listing 12.2 solves the problem of making extra copies and, thus, saves the calls to the copy constructor and destructor. It uses constant pointers to constant objects, thereby solving the problem of the called function making impermissible changes to the objects passed in as parameters. The method is still somewhat cumbersome, however, because the objects passed to the function are pointers.

Because you know the parameters will never be null, it would be easier to work with the function if references were passed in rather than pointers. Listing 12.3 rewrites Listing 12.2 to use references rather than pointers.

Listing 12.3. Passing References to Objects
 0: //Listing 12.3 1: // Passing references to ...

Get Sams Teach Yourself C++ in 24 Hours, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.