Implementing Inheritance 399
12
(1)dog (2)cat (0)Quit: 1
Woof
Woof
Mammal Speak!
(1)dog (2)cat (0)Quit: 2
Meow!
Meow!
Mammal Speak!
(1)dog (2)cat (0)Quit: 0
On lines 4–26, stripped-down versions of the Mammal,Dog, and Catclasses are
declared. Three functions are declared—PtrFunction(),RefFunction(), and
ValueFunction(). They take a pointer to a Mammal,a Mammalreference, and a Mammal
object, respectively. As you can see on lines 60–73, all three functions do the same
thing—they call the Speak()method.
The user is prompted to choose a Dogor a Cat, and based on the choice that is made, a
pointer to the correct type is created on lines 44 or 46.
In the first line of the output, the user chooses Dog. The Dogobject is created on the free
store on line 44. The Dogis then passed to a function as a pointer on line 53, as a refer-
ence on line 54, and by value on line 55.
The pointer and reference calls invoke the virtual functions, and the Dog->Speak()
member function is invoked. This is shown on the first two lines of output after the user’s
choice.
The dereferenced pointer, however, is passed by value on line 55 to the function on lines
60–63. The function expects a Mammalobject, and so the compiler slices down the Dog
object to just the Mammalpart. When the Mammal Speak()method is called on line 72,
only Mammalinformation is available. The Dogpieces are gone. This is reflected in the
third line of output after the user’s choice. This effect is called slicing because the Dog
portions (your derived class portions) of your object were sliced off when converting to
just a Mammal(the base class).
This experiment is then repeated for the Catobject, with similar results.
Creating Virtual Destructors ..........................................................................
It is legal and common to pass a pointer to a derived object when a pointer to a base
object is expected. What happens when that pointer to a derived subject is deleted? If the
destructor is virtual, as it should be, the right thing happens—the derived class’s destruc-
tor is called. Because the derived class’s destructor automatically invokes the base class’s
destructor, the entire object is properly destroyed.
OUTPUT
ANALYSIS