Thinking in C++ Vol 2 - Practical Programming |
Prev |
Home |
Next |
Because you can discover type information from an anonymous
polymorphic pointer, RTTI is ripe for misuse by the novice, because RTTI may make sense before virtual functions do. For many people coming from a
procedural background, it s difficult not to organize programs into sets of switch
statements. They could accomplish this with RTTI and thus lose the important
value of polymorphism in code development and maintenance. The intent of C++ is
that you use virtual functions throughout your code and that you only use RTTI
when you must.
However, using virtual functions as they are intended
requires that you have control of the base-class definition, because at some
point in the extension of your program you may discover the base class doesn t
include the virtual function you need. If the base class comes from a library
or is otherwise controlled by someone else, one solution to the problem is RTTI;
you can derive a new type and add your extra member function. Elsewhere in the
code you can detect your particular type and call that member function. This
doesn t destroy the polymorphism and extensibility of the program, because
adding a new type will not require you to hunt for switch statements. However,
when you add new code in the main body that requires your new feature, you ll
have to detect your particular type.
Putting a feature in a base class might mean that, for the
benefit of one particular class, all the other classes derived from that base
require some meaningless stub for a pure virtual function. This makes the
interface less clear and annoys those who must override pure virtual functions
when they derive from that base class.
Finally, RTTI will sometimes solve efficiency problems. If your code uses polymorphism in a nice way, but it turns out that one of your objects
reacts to this general-purpose code in a horribly inefficient way, you can pick
that type out using RTTI and write case-specific code to improve the efficiency.
Thinking in C++ Vol 2 - Practical Programming |
Prev |
Home |
Next |