Why doesn't the
dynamic_cast
in that line compile at all instead of just returning a NULL pointer?
Consider this as a feature/facility rather than a limitation.
dynamic_cast
is a mechanism where we would find the RTTI (run-time type information) of an object based on the pointer/reference.
Now suppose if a class is not at all polymorphic (i.e. doesn't contain any virtual
method), then definitely the dynamic_cast
will always fail.
Which means you don't have to use the dynamic_cast
where there is a 0 probability of passing. Why should you waste machine cycles on the thing which is known at compile time? That's why compiler provides you the facility straight away.
There is another hidden advantage of this. Suppose you are using dynamic_cast
with references, if it fails then an exception is thrown. Would anyone want to handle an exception for something which is already known at compile time!