I was checking the behavior of dynamic_cast and found that when it fails, std::bad_cast exception is thrown only if the destination is a reference type. If the destination is a pointer type then no exception is thrown from the cast. This is my sample code:
class A
{
public:
virtual ~A()
{
}
};
class B : public A
{
};
int main()
{
A* p = new A;
//Using reference
try
{
B& b = dynamic_cast<B&>(*p);
}
catch(std::bad_cast exp)
{
std::cout<<"Caught bad cast
";
}
//Using pointer
try
{
B* pB = dynamic_cast<B*>(p);
if( pB == NULL)
{
std::cout<<"NULL Pointer
";
}
}
catch(std::bad_cast exp)
{
std::cout<<"Caught bad cast
";
}
return 0;
}
Output is "Caught bad cast" and "NULL pointer". Code is compiled using VS2008. Is this the correct behavior ? If yes, then why there is a difference?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…