dynamic_cast throws unhandled exception during Reverse Polymorphism?

30 06 2008

What is Reverse Polymorphism?
Casting Base class object to derived class pointer is called Reverse Polymorphism or Inverse Polymorphism. Check the following code block.

// Base class.
class Base
    virtual ~Base() {}

// Derived class.
class Derived : public Base
    virtual ~Derived() {}

void CDialogDlg::OnButton4()
    // Base instance.
    Base* pBase = new Base;

    // Reverse Polymorphism. Cast Base Object to derived.
    Derived* pDerived = dynamic_cast<Derived*>( pBase );

While casting by using dynamic_cast, possible you may hit un-handled exception as follows.

Ideally dynamic_cast should return null, since its an invalid casting. But why its throwing un-handled exception? Is there something to do?

You’ve to enable RTTI. If RTTI is not enabled, it will throw un-handled exception for reverse polymorphism. For enabling RTTI,

1) Take project settings,
2) Take C/C++ tab.
3) In “C++ Language” category, enable RTTI. See the screenshot.

This is not a standard C++ behavior. This one is checked only in Visual C++ 6.0 compiler. You may or may not encounter the behavior in other Microsoft compiler version or in other compilers. So take care!

Targeted Audience – Intermediate.