In this link: http://www.cplusplus.com/doc/tutorial/typecasting/
When dynamic_cast cannot cast a pointer because it is not a complete object of the required class -as in the second conversion in the previous example- 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.
I couldnt understand from this text part, what are the exact conditions when dinamic_cast returns a null ptr, and when exception has been thrown.
If someone can please show me a two code samples that one of them return null ptr and the other is throwing an exception, it will be very appriciate. thanks.
Here is the difference:
DerivedClass *der = dynamic_cast<DerivedClass *>(someBaseClassPtr);
Will return nullptr in the case where someBaseClassPtr does not refer to an object of DerivedClass.
DerivedClass& der = dynamic_cast<DerivedClass&>(someBaseClassObj);
Will throw an exception if someBaseClassObj does not in fact reference an object of DerivedClass.
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