Multiple inheritance
RTTI must work with multiple complexities of multiple inherits, including virtual base classes (in the next chapter in-depth discussion - you can return here after reading Chapter 9).
//: c08: RTTIAndMultiPleinheritance.cpp
#include
#include
Using namespace std;
Class bb {
PUBLIC:
Virtual void f () {}
Virtual ~ bb () {}
}
Class B1: Virtual public bb {};
Class B2: Virtual public bb {};
Class MI: Public B1, Public B2 {};
Int main () {
BB * bbp = new mi; // Upcast
// Proper Name Detection:
COUT << TypeId (* bbp) .name () << endl;
// Dynamic_cast Works Properly:
Mi * MIP = Dynamic_Cast
// can't force Old-Style Cast:
//! MI * MIP2 = (mi *) bbp; // compile Error
} ///: ~
The TypeId () operates correctly detects the name of the actual object, even through a virtual base class pointer. Dynamic_cast also works correctly. But the compiler does not allow you to use the old way:
MI * MIP = (mi *) bbp; // compile-time Error
The compiler knows that this will never do the right thing, so it needs you to use a Dynamic_cast.
Use RTTI (SENSIBLE Uses for RTTI) correctly
Because you can discover type information from an anonymous polymorphic pointer, you can make sense before virtual functions, and RTTI is often misused by novices. For many people with process programming background, they do not use the Switch statement to organize the program into a collection. They may use RTTI to complete these, thus losing the importance of the code development and maintenance. C intent is to let you use virtual functions in your code, and use RTTI only when you must.
In any case, according to their intent, the virtual function requires you to have a base class definition of control, because when you expand your programs, sometimes you will find that the base class does not contain the virtual function you need. If the base class comes from a library or is controlled by others, the problem is RTTI, you can derive a new type and add your extra member functions. Other places in the code, you can detect your special type and call its member function. This does not destroy the polymorphism and program scalability, because adding a new type and requires you to search the Switch statement. However, when you join a new code to the main function you need your feature, you must detect your special type.