Null Pointers and Null References ......................................................................
When pointers are not initialized or when they are deleted, they ought to be assigned to
null ( 0 ). This is not true for references because they must be initialized to what they ref-
erence when they are declared.
However, because C++ needs to be usable for device drivers, embedded systems, and
real-time systems that can reach directly into the hardware, the ability to reference spe-
cific addresses is valuable and required. For this reason, most compilers support a null or
numeric initialization of a reference without much complaint, crashing only if you try to
use the object in some way when that reference would be invalid.
Taking advantage of this in normal programming, however, is still not a good idea. When
you move your program to another machine or compiler, mysterious bugs might develop
if you have null references.
Passing Function Arguments by Reference ........................................................
On Day 5, “Organizing into Functions,” you learned that functions have two limitations:
Arguments are passed by value, and the return statement can return only one value.
Passing values to a function by reference can overcome both of these limitations. In C++,
passing a variable by reference is accomplished in two ways: using pointers and using
references. Note the difference: You pass by referenceusing a pointer, or you pass aref-
erenceusing a reference.
The syntax of using a pointer is different from that of using a reference, but the net effect
is the same. Rather than a copy being created within the scope of the function, the actual
original object is (effectively) made directly available to the function.
262 Day 9
References
References act as an alias to another variable. 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.
Example 1
int hisAge;
int &rAge = hisAge;
Example 2
Cat Boots;
Cat &rCatRef = Boots;