Thinking in C++ Vol 2 - Practical Programming |
Prev |
Home |
Next |
The RTTI mechanisms must work properly with all the complexities of multiple inheritance, including virtual base
classes (discussed in depth in the next chapter you may want to come back here
after reading Chapter 9):
//: C08:RTTIandMultipleInheritance.cpp
#include <iostream>
#include <typeinfo>
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<MI*>(bbp);
// Can't force old-style cast:
//! MI* mip2 = (MI*)bbp; // Compile error
} ///:~
The typeid( ) operator properly detects
the name of the actual object, even through the virtual base class
pointer. The dynamic_cast also works correctly. But the compiler won t
even allow you to try to force a cast the old way:
MI* mip = (MI*)bbp; // Compile-time error
The compiler knows this is never the right thing to do, so
it requires that you use a dynamic_cast.
Thinking in C++ Vol 2 - Practical Programming |
Prev |
Home |
Next |