Sams Teach Yourself C++ in 21 Days

(singke) #1
Polymorphism 487

14


You also learned what abstract classes are and how to create abstract classes using pure
virtual functions. You learned how to implement pure virtual functions and when and
why you might do so.

Q&A ....................................................................................................................


Q What is the v-ptr?
A The v-ptr, or virtual-function pointer, is an implementation detail of virtual func-
tions. Each object in a class with virtual functions has a v-ptr, which points to the
virtual function table for that class. The virtual function table is consulted when the
compiler needs to determine which function to call in a particular situation.
Q Is percolating upward always a good thing?
A Yes, if you are percolating shared functionality upward. No, if all you are moving
is interface. That is, if all the derived classes can’t use the method, it is a mistake
to move it up into a common base class. If you do, you’ll have to switch on the
runtime type of the object before deciding if you can invoke the function.
Q Why is making a decision on the runtime type of an object bad?
A Because this is an indication that the inheritance hierarchy for the class has not
been properly constructed, and it is better to go back and fix the design than to use
this workaround.
Q Why is casting bad?
A Casting isn’t bad if it is done in a way that is type-safe. Casting can, however, be
used to undermine the strong type checking in C++, and that is what you want to
avoid. If you are switching on the runtime type of the object and then casting a
pointer, that might be a warning sign that something is wrong with your design.
In addition, functions should work with the declared type of their arguments and
member variables, and not depend on “knowing” what the calling program will
provide through some sort of implicit contract. If the assumption turns out to be
wrong, strange and unpredictable problems can result.
Q Why not make all functions virtual?
A Virtual functions are supported by a virtual function table, which incurs runtime
overhead, both in the size of the program and in the performance of the program. If
you have very small classes that you don’t expect to subclass, you might not want
to make any of the functions virtual. However, when this assumption changes, you
need to be careful to go back and make the ancestor class functions virtual, or
unexpected problems can result.
Free download pdf