Why Base-to-Derived Dynamic Casting is Only Allowed for Polymorphic Classes [duplicate]
-
27-10-2019 - |
Question
Possible Duplicate:
FAQ: Why does dynamic_cast only work if a class has at least 1 virtual method?
I have read that in C++, performing a dynamic cast down the hierarchy of a set of classes, the cast is allowed only in a situation where the classes are polymorphic, such as when the base class is having a virtual function, etc. What is the reason for this limitation? Is it more 'safe' to have a pure virtual function in place of the normal virtual function in the base class?
Thank You!
Solution
What is the reason for this limitation?
dynamic_cast
is only supposed to succeed when the object is an instance of the target type.
Non-polymorphic classes don't contain any type information, so there is no way to tell whether this is the case; therefore, the cast cannot succeed.
Is it more 'safe' to have a pure virtual function in place of the normal virtual function in the base class?
Either is fine, as far as polymorphism is concerned. If the base class has at least one virtual function, then it is polymorphic, and so can be used with dynamic_cast
. Whether it's pure or not only affects whether the base class can be instantiated.
OTHER TIPS
It's a limitation induced by the standard.
In major implementations, dynamic_cast
works by comparing the vfptr
- virtual function table pointer - of two classes.
That's one way to determine whether classes are related at run-time. Besides, it wouldn't really make sense to do a dynamic_cast
on non-polymorphic classes. There's static_cast
for that.
My guess is that you're doing something wrong, if you're trying to use dynamic_cast
on non-polymorphic classes. If you post some code, we could help.
When performing a dynamic_cast
there is a type check performed at a runtime and std::bad_cast
exception is thrown or null pointer is returned when the cast is illegal.
The mechanism allowing to do this is called RTTI.
When class are not polymorphic there is no way to perform that typecheck, because no type information is stored at the runtime.