dynamic_cast requires virtual functions (polymorphic), why?

First of all, if you ALREADY know the cast is safe, static_cast can replace dynamic_cast, even in mutilple inheritance, except virtual inheritance.
Please see this post for why.

struct D: virtual B {...};//have to use dynamic_cast to cast B* to D*

I have to go through a few steps to explain this.
1. dynamic_cast needs access to RTTI (again, the above link says why).
2. RTTI is only accessable through vtable pointer.
3. no virtual functions, no vtable pointer. (RTTI can sit right above vtable)
4. Conclusion, dynamic_cast needs virtual function.

Comments are closed.
%d bloggers like this: