Sams Teach Yourself C++ in 21 Days

(singke) #1

Summary ..............................................................................................................


Today, you learned what references are and how they compare to pointers. You saw that
references must be initialized to refer to an existing object and cannot be reassigned to
refer to anything else. Any action taken on a reference is in fact taken on the reference’s
target object. Proof of this is that taking the address of a reference returns the address of
the target.
You saw that passing objects by reference can be more efficient than passing by value.
Passing by reference also allows the called function to change the value in the arguments
back in the calling function.
You saw that arguments to functions and values returned from functions can be passed
by reference, and that this can be implemented with pointers or with references.
You saw how to use pointers to constant objects and constant references to pass values
between functions safely while achieving the efficiency of passing by reference.

Q&A ....................................................................................................................


Q Why have references if pointers can do everything references can?
A References are easier to use and to understand. The indirection is hidden, and no
need exists to repeatedly dereference the variable.
Q Why have pointers if references are easier?
A References cannot be null, and they cannot be reassigned. Pointers offer greater
flexibility but are slightly more difficult to use.
Q Why would you ever return by value from a function?
A If the object being returned is local, you must return by value or you will be return-
ing a reference to a nonexistent object.
Q Given the danger in returning by reference, why not always return by value?
A Far greater efficiency is achieved in returning by reference. Memory is saved and
the program runs faster.

286 Day 9


DOpass parameters by value when you
must.
DOreturn by value when you must.

DON’Tpass by reference if the item
referred to might go out of scope.
DON’Tlose track of when and where
memory is allocated so you can be cer-
tain it is also freed.

DO DON’T

Free download pdf