Like the other answers here, you cannot use reinterpret_cast this way because the value of the pointer to base actually different from the value of the pointer to derived . A valid pointer is output at runtime, so you should use dynamic_cast . static_cast cannot work, because you do not know at design time through which intermediate type the most derived class (the one you want to use) was obtained from the type you have a pointer to.
The real question here should be: I know at design time how to calculate the derived pointer with the base pointer. How to avoid runtime limitation ( dynamic_cast )?
Frankly, I donβt see a really good option here, but a possible possibility is to save the pointer to the most derived type in a constant pointer inside the root class, for example:
struct base { void* const self; virtual ~base() {} protected: base(void* self) : self(self) {} }; struct derived : public virtual base { derived() : base(this) {} }
This is ugly and dangerous because it sacrifices type safety for performance (if you are really lucky, you get little performance at runtime). But you can reinterpret_cast a base pointer (a member of self type void* ) into a derived pointer.
source share