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?
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.
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).
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).
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With