I’ve noticed with regard to the std::bad_cast exception that references and pointers don’t seem to act the same way. For example:
class A { public: ~A() {} };
class B : public A {};
//Case #1
int main()
{
A a;
B& b = dynamic_cast<B&>(a); //Would throw std::bad_cast.
}
//Case #2
int main()
{
A* a = new A;
B* b = dynamic_cast<B*>(a); //Would not throw std::bad_cast.
}
In the first case, an exception of std::bad_cast is generated, and in the second case no exception is generated – instead, the b pointer just is assigned the value NULL.
Can someone explain to me why only the former throws an exception when both are bad_cast examples? I figure there’s a good motive behind the decision, and that I’m misusing something as I don’t understand that motivation.
That is how
dynamic_castis specified to behave: a baddynamic_castinvolving pointers yields a null pointer, but there are no null references, so a baddynamic_castinvolving references throws abad_cast.The fact that a failed
dynamic_castinvolving pointers yields a null pointer is useful because it allows for cleaner, simpler type checking and allows for the following idiom:With this idiom,
bis in scope and usable if and only if it is non-null.