20

According to what I read, performing a wrong run-time dynamic_cast can either throw a bad_cast exception or return zero.

Is it correct to say that it will return zero if you are casting pointers?

i.e:

class Base { virtual void a(){} };
class Derived: public Base {};

int main () {
  Base *base = new Base();
  dynamic_cast<Derived*>(base);
  return 0;
} 

And that it will throw an bad_cast exception when casting objects?

i.e:

class Base { virtual void a(){} };
class Derived: public Base {};

int main () {
  Base base;
  Base& ref = base;
  dynamic_cast<Derived&>(ref);
  return 0;
}
Sisir
  • 4,584
  • 4
  • 26
  • 37
NIGO
  • 863
  • 2
  • 10
  • 16

1 Answers1

36

dynamic_cast will return NULL on a bad cast if you are casting a pointer; it will throw std::bad_cast when casting references. It is a compile-time error to attempt to cast objects with dynamic_cast (eg, with dynamic_cast<Derived>(base))

bdonlan
  • 224,562
  • 31
  • 268
  • 324
  • Ok, so the affirmation is correct. Thanks. I edited the message in order to make the base class polymorphic (adding the virtual function) and using reference casting for the exception to be thrown. – NIGO Aug 30 '11 at 02:45