|
|
 |
|
|
|
|
62: }
63:
64: void PtrFunction (Mammal * pMammal)
65: {
66: pMammal->Speak();
67: }
68:
69: void RefFunction (Mammal & rMammal)
70: {
71: rMammal.Speak();
72: } |
|
|
|
|
|
|
|
|
(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 |
|
|
|
|
|
|
|
|
Analysis: On lines 525, stripped-down versions of the Mammal, Dog, and Cat classes are declared. Three functions are declaredPtrFunction(), RefFunction(), and ValueFunction(). They take a pointer to a Mammal, a Mammal reference, and a Mammal object, respectively. All three functions then do the same thingthey call the Speak() method. |
|
|
|
|
|
|
|
|
The user is prompted to choose a Dog or Cat; based on the choice he makes, a pointer to the correct type is created on lines 4348. |
|
|
|
|
|
|
|
|
In the first line of the output, the user chooses Dog. The Dog object is created on the free store in line 43. The Dog is then passed as a pointer, as a reference, and by value to the three functions. |
|
|
|
|
|
|
|
|
The pointer and references all invoke the virtual member 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. The function expects a Mammal object, so the compiler slices down the Dog object to just the Mammal part. At that point, the Mammal Speak() method is called, as reflected in the third line of output after the user's choice. |
|
|
|
|
|
|
|
|
This experiment is then repeated for the Cat object, with similar results. |
|
|
|
|
|