Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Safe" dynamic cast?

Tags:

c++

oop

casting

I'm familiar with how to do a dynamic cast in C++, as follows:

myPointer = dynamic_cast<Pointer*>(anotherPointer);

But how do you make this a "safe" dynamic cast?

like image 324
user3308043 Avatar asked Mar 31 '14 05:03

user3308043


People also ask

Is dynamic cast Safe?

If you pass a dangling pointer or a value that is garbage, then the call to dynamic_cast is not guaranteed to be safe. In fact, the best case scenario is that the run time system throws an exception and you can deal with it. The worst case scenario is that it is undefined behavior.

What happens if dynamic cast fails?

If a dynamic_cast fails, the result of the conversion will be a null pointer. Because we haven't checked for a null pointer result, we access d->getName(), which will try to dereference a null pointer, leading to undefined behavior (probably a crash).

What does dynamic cast do?

In C++, dynamic casting is, primarily, used to safely downcast; i.e., cast a base class pointer (or reference) to a derived class pointer (or reference). It can also be used for upcasting; i.e., casting a derived class pointer (or reference) to a base class pointer (or reference).

Is dynamic cast a code smell?

Yes, dynamic_cast is a code smell, but so is adding functions that try to make it look like you have a good polymorphic interface but are actually equal to a dynamic_cast i.e. stuff like can_put_on_board .


1 Answers

When dynamic_cast cannot cast a pointer because it is not a complete object of the required class it returns a null pointer to indicate the failure. If dynamic_cast is used to convert to a reference type and the conversion is not possible, an exception of type bad_cast is thrown instead.

like image 199
humam Avatar answered Oct 13 '22 14:10

humam