|
|
 |
|
|
|
|
73: break;
74: }
75: theArray[i] = ptr;
76: }
77: Mammal *OtherArray[NumAnimalTypes];
78: for (i=0;i<NumAnimalTypes;i++)
79: {
80: theArray[i]->Speak();
81: OtherArray[i] = theArray[i]->Clone();
82: }
83: for (i=0;i<NumAnimalTypes;i++)
84: OtherArray[i]->Speak();
85: return 0;
86: } |
|
|
|
|
|
|
|
|
1: (1)dog (2)cat (3)Mammal: 1
2: Mammal constructor
3: Dog Constructor
4: (1)dog (2)cat (3)Mammal: 2
5: Mammal constructor
6: Cat constructor
7: (1)dog (2)cat (3)Mammal: 3
8: Mammal constructor
9: Woof!
10: Mammal copy constructor
11: Dog copy constructor
12: Meow!
13: Mammal copy constructor
14: Cat copy constructor
15: Mammal speak!
16: Mammal copy constructor
17: Woof!
18: Meow!
19: Mammal speak! |
|
|
|
|
|
|
|
|
Analysis: Listing 17.4 is very similar to the previous two listings, except that a new virtual method has been added to the Mammal class: clone(). This method returns a pointer to a new Mammal object by calling the copy constructor, passing in itself (*this) as a const reference. |
|
|
|
|
|
|
|
|
Dog and Cat both override the clone() method, initializing their data and passing in copies of themselves to their own copy constructors. Because clone() is virtual, this will effectively create a virtual copy constructor, as shown on line 81. |
|
|
|
|
|
|
|
|
The user is prompted to choose dogs, cats, or mammals, and these are created on lines 6873. A pointer to each choice is stored in an array on line 75. |
|
|
|
|
|