Sams Teach Yourself C++ in 21 Days

(singke) #1
In this example, a pointer to int,pInt, is declared and initialized with the memory
returned by the operator new. The address in pIntis tested, and if it is not null,pIntis
dereferenced. The result of dereferencing an intvariable is an intobject, and rIntis
initialized to refer to that object. Thus,rIntbecomes an alias to the intreturned by the
operator new.

280 Day 9


DOpass parameters by reference when-
ever possible.
DOuse constto protect references and
pointers whenever possible.

DON’Tuse pointers if references will
work.
DON’Ttry to reassign a reference to a
different variable. You can’t.

DO DON’T


Mixing References and Pointers..........................................................................


It is perfectly legal to declare both pointers and references in the same function parame-
ter list, along with objects passed by value. Here’s an example:
Cat * SomeFunction (Person &theOwner, House *theHouse, int age);
This declaration says that SomeFunctiontakes three parameters. The first is a reference
to a Personobject, the second is a pointer to a Houseobject, and the third is an integer. It
returns a pointer to a Catobject.
The question of where to put the reference (&) or the indirection operator (*) when
declaring these variables is a great controversy. When declaring a reference, you can
legally write any of the following:
1: Cat& rFrisky;
2: Cat & rFrisky;
3: Cat &rFrisky;
Whitespace is completely ignored, so anywhere you see a space here you can put as
many spaces, tabs, and new lines as you want.
Setting aside freedom of expression issues, which is best? Here are the arguments for
all three:
The argument for case 1 is that rFriskyis a variable whose name is rFriskyand whose
type can be thought of as “reference to Catobject.” Thus, this argument goes, the &
should be with the type.
Free download pdf