2

I still wonder why the following gives std::bad_cast exception

#include <typeinfo>
class A {virtual void fun() {}};
class B : public A {};
int main() {
    try { 
       A a; 
       B b = dynamic_cast<B&>(a);
    } catch (std::bad_cast& e) {
       std::cerr << e.what() << '\n';
    }
}

class A is a polymorphic class class B is publicly derived from A properly doing a downcast from base class A object through reference, dynamic_cast does accept a reference argument but still why this exception?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Ibrahim Quraish
  • 3,889
  • 2
  • 31
  • 39

2 Answers2

4

This is what dynamic_cast supposed to do. a is an object of A in fact, converting it to the derived class B would fail. On the other hand, if you convert something with type of reference or pointer to the base class, but refers to an object of B in fact, then it will work fine. e.g.

B b1;
A& ra = b1;
B b2 = dynamic_cast<B&>(ra);
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
3

What you've basically said is "I have an animal, but is it a lion?"

And the language needs to be able to say either "yes it is a lion" or "no it is not a lion".

When you cast to a pointer type, it can say "no" by returning nullptr to you or the actual pointer to a lion if "yes"

However, there's no such thing as a null reference. Because of this, when you cast to a reference, it needs a different mechanism to inform you that your animal isn't a lion. It throws a bad cast exception in that case.

xaxxon
  • 19,189
  • 5
  • 50
  • 80