< previous page page_279 next page >

Page 279
As the program iterates over the array, each object has its Speak() and its Clone() method called, in turn, on lines 80 and 81. The result of the Clone() call is a pointer to a copy of the object, which is then stored in a second array on line 81.
On line 1 of the output, the user is prompted and responds with 1, choosing to create a dog. The Mammal and Dog constructors are invoked. This is repeated for Cat and for Mammal on lines 48 of the constructor.
Line 9 of the output represents the call to Speak on the first object, the Dog. The virtual Speak() method is called, and the correct version of Speak() is invoked. The Clone() function is then called, and as this is also virtual, Dog's Clone method is invoked, causing the Mammal constructor and the Dog copy constructor to be called.
The same is repeated for Cat on lines 1214, and then for Mammal on lines 15 and 16. Finally, the new array is iterated, and each of the new objects has Speak() invoked.
The Cost of Virtual Methods
Because objects with virtual methods must maintain a v-table, there is some overhead in having virtual methods. If you have a very small class from which you do not expect to derive other classes, there might be no reason to have any virtual methods at all.
After you declare any methods virtual, you've paid most of the price of the v-table (although each entry does add a small memory overhead). At that point, you'll want the destructor to be virtual, and the assumption will be that all other methods probably will be virtual as well. Take a long hard look at any non-virtual methods, and be certain you understand why they are not virtual.
DODON'T
DO use virtual methods when you expect to derive from a class.DON'T mark the constructor as virtual.
DO use a virtual destructor if any methods are virtual.

Summary
In this hour, you learned how to use virtual member functions to enable your derived classes to behave polymorphically with their base classes.
In classes with virtual methods, the destructor should almost always be made virtual. A virtual destructor ensures that the derived part of the object will be freed when delete is called on the pointer. Constructors cannot be virtual. Virtual copy constructors can be effectively created by making a virtual member function that calls the copy constructor.

 
< previous page page_279 next page >

If you like this book, buy it!