Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does dynamic_cast return 0 and when throws exception? cpp

Tags:

c++

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.

like image 312
ede wd Avatar asked May 30 '26 12:05

ede wd


1 Answers

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.

like image 114
Mikel F Avatar answered Jun 02 '26 03:06

Mikel F



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!