The basic rules for dynamic_cast
The rules are rather complicated, especially when:
There is multiple inheritance
We cast to or from the type void*
We are just going to look at some basic cases.
The rules are rather complicated, especially when:
There is multiple inheritance
We cast to or from the type void*
We are just going to look at some basic cases.
Assume furthermore that class D is derived from B directly or indirectly, that is, through multiple layers of inheritance.
Due to inheritance, D is also a polymorphic type.
The dynamic_cast from D* (up) to B* succeeds.
This is known as an upcast.
The dynamic_cast from B* (down) to D* fails.
This is known as an downcast.
The dynamic_cast from B* to B* succeeds, as does the dynamic_cast from D* to D*.
Both have virtual functions, either declared directly or through inheritance.
Then:
The dynamic_cast from Apple* to Orange* fails.
The dynamic_cast from Orange* to Apple* fails.
Generally, casts involving unrelated types, other than void*, fail.