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!
dynamic_castis 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.
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.