-1
#include <iostream>
using namespace std;

struct A
{
    virtual void foo() { }
};
struct B1 :A
{
};

int main()
{
    int x = 42;
    A *a = (A*)&x;
    try
    {
        B1 *b = dynamic_cast<B1*>(a);
    }
    catch (...)
    {
        cout << "what kind of exception is here now?";
    }
    return 0;
}

What type of exception I catch?

What else can I write inside parentheses: catch (...) to catch this exception as well?

Luk Rob
  • 19
  • 4

1 Answers1

3

A dynamic_cast between pointer types will never throw, it will simply return nullptr. If you want dynamic_cast to throw, convert between reference types. The exception will be of type std::bad_cast.

From http://en.cppreference.com/w/cpp/language/dynamic_cast :

If the cast fails and new_type is a pointer type, it returns a null pointer of that type. If the cast fails and new_type is a reference type, it throws an exception that matches a handler of type std::bad_cast.

François Andrieux
  • 28,148
  • 6
  • 56
  • 87