Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in behavior while using dynamic_cast with reference and pointers

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\n";     }      //Using pointer       try     {     B* pB = dynamic_cast<B*>(p);      if( pB == NULL)     {         std::cout<<"NULL Pointer\n";     }     }     catch(std::bad_cast exp)     {     std::cout<<"Caught bad cast\n";     }      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?

like image 958
Naveen Avatar asked Aug 14 '09 09:08

Naveen


People also ask

What is the behavior of dynamic_cast when down casting is detected on pointers?

So when dynamic_cast for a pointer type fails it returns a null pointer and the caller can check for that, but when it fails for a reference type it can't return a null reference, so an exception is the only reasonable way to signal a problem.

What does dynamic cast of a reference return if it fails?

If the cast is successful, dynamic_cast returns a value of type new-type. 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.

Can dynamic cast be used with references?

The dynamic_cast operator can be used to cast to reference types. C++ reference casts are similar to pointer casts: they can be used to cast from references to base class objects to references to derived class objects.

Why dynamic_cast is used in C++?

The primary purpose for the dynamic_cast operator is to perform type-safe downcasts. A downcast is the conversion of a pointer or reference to a class A to a pointer or reference to a class B , where class A is a base class of B .


1 Answers

Yes, this is correct behaviour. The reason is that you can have a null pointer, but not a null reference - any reference has to be bound to an object.

So when dynamic_cast for a pointer type fails it returns a null pointer and the caller can check for that, but when it fails for a reference type it can't return a null reference, so an exception is the only reasonable way to signal a problem.

like image 149
sharptooth Avatar answered Nov 08 '22 20:11

sharptooth