Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Thinking In C++, 2nd Edition, Volume 2 Standard Libraries& Advanced Topics - Eckel B..pdf
Скачиваний:
319
Добавлен:
24.05.2014
Размер:
2.09 Mб
Скачать

class X { public: virtual ~X(){} }; class B { public: virtual ~B(){} }; class D : public B {};

int main() { D d;

B & b = d; // Upcast to reference try {

X& xr = dynamic_cast<X&>(b);

}catch(...) {

cout << "dynamic_cast<X&>(b) failed"

<< endl;

}

X* xp = 0; try {

typeid(*xp); // Throws exception

}catch(bad_typeid) {

cout << "Bad typeid() expression" << endl;

}

} ///:~

The failure, of course, is because b doesn’t actually point to an X object. If an exception was not thrown here, then xr would be unbound, and the guarantee that all objects or references are constructed storage would be broken.

An exception is also thrown if you try to dereference a null pointer in the process of calling typeid( ). The Standard C++ exception is called bad_typeid.

Here (unlike the reference example above) you can avoid the exception by checking for a nonzero pointer value before attempting the operation; this is the preferred practice.

Multiple inheritance

Of course, the RTTI mechanisms must work properly with all the complexities of multiple inheritance, including virtual base classes:

//: C08:RTTIandMultipleInheritance.cpp #include <iostream>

#include <typeinfo> using namespace std;

class BB { public:

virtual void f() {}

Chapter 17: Run-Time Type Identification

411

Соседние файлы в предмете Программирование