Working with Advanced Functions 301
10
On lines 6–19, the Catclass is declared. Note that on line 9 a default constructor
is declared, and on line 10 a copy constructor is declared. You know this is a
copy constructor on line 10 because the constructor is receiving a reference—a constant
reference in this case—to an object of its same type.
On lines 17 and 18, two member variables are declared, each as a pointer to an integer.
Typically, there is little reason for a class to store intmember variables as pointers, but
this was done to illustrate how to manage member variables on the free store.
The default constructor on lines 21–27 allocates room on the free store for two intvari-
ables and then assigns values to them.
The copy constructor begins on line 29. Note that the parameter is rhs. It is common to
refer to the parameter to a copy constructor as rhs, which stands for right-hand side.
When you look at the assignments on lines 33 and 34, you’ll see that the object passed in
as a parameter is on the right-hand side of the equal sign. Here’s how it works:
On lines 31 and 32, memory is allocated on the free store. Then, on lines 33 and 34, the
value at the new memory location is assigned the values from the existing Cat.
The parameter rhsis a Catobject that is passed into the copy constructor as a constant
reference. As a Catobject,rhshas all the member variables of any other Cat.
Any Catobject can access private member variables of any other Catobject; however, it
is good programming practice to use public accessor methods when possible. The mem-
ber function rhs.GetAge()returns the value stored in the memory pointed to by rhs’s
member variable itsAge. In a real-world application, you should get the value for
itsWeightin the same way—using an accessor method. On line 34, however, you see
confirmation that different objects of the same class can access each other’s members. In
this case, a copy is made directly from the rhsobject’s private itsWeightmember.
Figure 10.3 diagrams what is happening here. The values pointed to by the existing Cat’s
member variables are copied to the memory allocated for the new Cat.
On line 47, a Catcalled Friskyis created. Frisky’s age is printed, and then his age is set
to 6 on line 50. On line 52, a new Cat,Boots, is created, using the copy constructor and
passing in Frisky. Had Friskybeen passed as a parameter to a function by value (not by
reference), this same call to the copy constructor would have been made by the compiler.
On lines 53 and 54, the ages of both Cats are printed. Sure enough,Bootshas Frisky’s
age, 6 , not the default age of 5. On line 56,Frisky’s age is set to 7 , and then the ages are
printed again. This time Frisky’s age is 7 , but Boots’s age is still 6 , demonstrating that
they are stored in separate areas of memory.
ANALYSIS