Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
B.Eckel - Thinking in C++, Vol.2, 2nd edition.pdf
Скачиваний:
50
Добавлен:
08.05.2013
Размер:
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

Соседние файлы в предмете Численные методы
  • #
    08.05.20133.99 Mб22A.Menezes, P.van Oorschot,S.Vanstone - HANDBOOK OF APPLIED CRYPTOGRAPHY.djvu
  • #
  • #
    08.05.20135.91 Mб24B.Eckel - Thinking in Java, 3rd edition (beta).pdf
  • #
  • #
    08.05.20136.09 Mб17D.MacKay - Information Theory, Inference, and Learning Algorithms.djvu
  • #
    08.05.20133.85 Mб15DIGITAL Visual Fortran ver.5.0 - Programmers Guide to Fortran.djvu
  • #
    08.05.20131.84 Mб12E.A.Lee, P.Varaiya - Structure and Interpretation of Signals and Systems.djvu