Sams Teach Yourself C++ in 21 Days

(singke) #1
Implementing Inheritance 403

12


As the program iterates over the array on lines 78 to 82, each object has its Speak()and
its Clone()methods called, in turn. The result of the Clone()call on line 81 is a pointer
to a copy of the object, which is then stored in a second array.
On line 1 of the output, the user is prompted and responds with 1 , choosing to create a
dog. The Mammaland Dogconstructors are invoked. This is repeated for Caton line 4 and
for Mammalon line 8 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 because this is also virtual,Dog’s Clone()method is invoked,
causing the Mammalconstructor and the Dogcopy constructor to be called.
The same is repeated for Caton lines 12–14, and then for Mammalon lines 15 and 16.
Finally, the new array is iterated on lines 83 and 84 of the listing, and each of the new
objects has Speak()invoked, as can be seen by output lines 17 to 19.

The Cost of Virtual Methods ..........................................................................


Because objects with virtual methods must maintain a v-table, some overhead occurs in
having virtual methods. If you have a very small class from which you do not expect to
derive other classes, there might not be a 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 want the
destructor to be virtual, and the assumption is that all other methods probably are virtual
as well. Take a long, hard look at any nonvirtual methods, and be certain you understand
why they are not virtual.

DOuse virtual methods when you expect
to derive from a class.
DOuse a virtual destructor if any meth-
ods are virtual.

DON’Tmark the constructor as virtual.
DON’Ttry to access private data in a
base class from a derived class.

DO DON’T


Summary ..............................................................................................................


Today, you learned how derived classes inherit from base classes. Today’s class discussed
public inheritance and virtual functions. Classes inherit all the public and protected data
and functions from their base classes.
Free download pdf