dyn_cast.cpp
Upload User: dq031136
Upload Date: 2022-08-08
Package Size: 802k
Code Size: 1k
Development Platform:

C++ Builder

  1. // NOTE: You must compile this program with your compiler's Generate RTTI option enabled.
  2. #include <iostream.h>
  3. #include <typeinfo.h>
  4. class Base1
  5. {
  6.    virtual void f(void) { /* A virtual function makes the class polymorphic */ }
  7. };
  8. class Base2 { };
  9. class Derived : public Base1, public Base2 { };
  10. void main(void) 
  11. {
  12.    try 
  13.    {
  14.       Derived d, *pd;
  15.       Base1 *b1 = &d;
  16.       // Perform a downcast from a Base1 to a Derived.
  17.       if ((pd = dynamic_cast<Derived *>(b1)) != 0) 
  18.   {
  19.            cout << "The resulting pointer is of type "
  20.                 << typeid(pd).name() << endl;
  21.          }
  22.       else throw Bad_cast();
  23.       // Cast from the first base to the most derived class and then back
  24.       // to another accessible base.
  25.       Base2 *b2;
  26.       if ((b2 = dynamic_cast<Base2 *>(b1)) != 0) 
  27.   {
  28.           cout << "The resulting pointer is of type "
  29.                << typeid(b2).name() << endl;
  30.          }
  31.       else throw Bad_cast();
  32.       }
  33.    catch (Bad_cast) 
  34.    {
  35.       cout << "dynamic_cast failed" << endl;
  36.       exit(1);
  37.       }
  38.    catch (...) {
  39.       cout << "Exception handling error." << endl;
  40.       exit(1);
  41.       }
  42. }