Line 8 contains the second constructor definition. In this overloaded version, two
parameters are passed. These parameters are then set to the class’s members on lines 9
and 10.
Some variables must be initialized and cannot be assigned to, such as references and
constants. It is common to have other assignments or action statements in the body of the
constructor; however, it is best to use initialization as much as possible.
The Copy Constructor..........................................................................................
In addition to providing a default constructor and destructor, the compiler provides a
default copy constructor. The copy constructor is called every time a copy of an object
is made.
As you learned on Day 9, “Exploiting References,” when you pass an object by value,
either into a function or as a function’s return value, a temporary copy of that object is
made. If the object is a user-defined object, the class’s copy constructor is called. You
saw this yesterday in Listing 9.6.
All copy constructors take one parameter, a reference to an object of the same class. It is
a good idea to make it a constant reference because the constructor will not have to alter
the object passed in. For example,
Cat(const Cat & theCat);
Here, the Catconstructor takes a constant reference to an existing Catobject. The goal
of this copy constructor is to make a copy of theCat.
The default copy constructor simply copies each member variable from the object passed
as a parameter to the member variables of the new object. This is called a member-wise
(or shallow) copy, and although this is fine for most member variables, it breaks pretty
quickly for member variables that are pointers to objects on the free store.
A shallow or member-wise copy copies the exact values of one object’s member vari-
ables into another object. Pointers in both objects end up pointing to the same memory.
A deep copy copies the values allocated on the heap to newly allocated memory.
If the Catclass includes a member variable,itsAge, that is a pointer to an integer on the
free store, the default copy constructor copies the passed-in Cat’s itsAgemember vari-
able to the new Cat’s itsAgemember variable. The two objects now point to the same
memory, as illustrated in Figure 10.1.
This leads to a disaster when either Catgoes out of scope. If the original Cat’s destructor
frees this memory and the new Catis still pointing to the memory, a stray pointer has
been created, and the program is in mortal danger. Figure 10.2 illustrates this problem.
298 Day 10