Sponsored Link •
Bill Venners: You said in the first edition of Effective C++:
Fortunately, C++ provides no way to determine at runtime the actual type of object a pointer points to, and let me assure you this is no accident. In fact, runtime type inquiry (RTTI) was explicitly omitted from the language to prevent abuses such as this.
Doesn't C++ have RTTI now?
Scott Meyers: Yes.
Bill Venners: When is it appropriate to use RTTI?
Scott Meyers: Let me give you some history on why the committee added RTTI to the C++ language. This is one of those cases where the consumers won. At the time, every non-trivial class library being written was rolling its own RTTI, without exception. Every major class library used at the time, including MFC (Microsoft Foundation Classes) and NIHCL (National Institute of Health Class Library), had RTTI of some form or another. So the committee just said, "Rather than have N different ways to accomplish the same thing, we're going to have a single language mechanism that does the right thing." That's why RTTI was added. It was a simple matter of people wanted it.
Once the committee added RTTI, people started wondering when it was appropriate to use RTTI. All the bad things I wrote about RTTI in the first edition of Effective C++ continue to apply. They're still bad. So you end up with a classic engineering tradeoff. You use RTTI when the alternatives are worse.
The two most common ways to eliminate RTTI are to add virtual functions higher in
the hierarchy and to hold onto a derived class interface by not promoting the derived
class type to its base class type. For example, if you can replace RTTI with virtual
function calls by modifying a base class, that's usually a better way to go. The other
approach, eliminating the need to upcast in the first place, is especially appropriate in
C++, because C++ has type-safe containers. C++ has no
Object class like
Java or C#. So instead of having, for example, a container of base class pointers, you can
have three containers, one for each different type of derived class you're dealing with.
Then you'll never lose the type information and you'll never have to do the downcast, so
you don't need RTTI.
In many cases, however, you can't do either of those two things to avoid using RTTI. Perhaps you will lose type information, because you will promote a derived class pointer or reference to a base class type. Perhaps you can't modify the base class to add virtual functions, or it just doesn't make any sense to add virtual functions to the base class. What do you do? My advice is, use a safe downcast. C++ has RTTI in the language now. You can do a downcast, and it will tell you at runtime whether the downcast succeeded.