dynamic_cast from "void *"

In 5.2.7 - Dynamic cast [expr.dynamic.cast] it says that for dynamic_cast<T>(v):

  • If T is a pointer type, v shall be an rvalue of a pointer to complete class type
  • If T is a reference type, v shall be an lvalue of a complete class type (thanks usta for commenting on my missing this)

...

  • Otherwise, v shall be a pointer to or an lvalue of a polymorphic type

So, no, a (void*) value is not allowed.

Let's think about what your request might mean: say you've got a pointer that's really to a Derived1*, but the code dynamic_cast-ing only knows it's a void*. Let's say you're trying to cast it to a Derived2*, where both derived classes have a common base. Superficially, you might think all the pointers would point to the same Base object, which would contain a pointer to the relevant virtual dispatch table and RTTI, so everything could hang together. But, consider that derived classes may have multiple base classes, and therefore the needed Base class sub-object might not be the one to which the Derived* - available only as a void* - is pointing. It wouldn't work. Conclusion: the compiler needs to know these types so it can perform some adjustment to the pointers based on the types involved.

Derived1* -----> [AnotherBase]
                 [[VDT]Base]    <-- but, need a pointer to start of
                 [extra members]    this sub-object for dynamic_cast

(Some answers talk about the need for the pointer you're casting from to be of a polymorphic type, having virtual functions. That's all valid, but a bit misleading. As you can see above, even if the void* is to such a type it still wouldn't work reliably without the full type information, as the real problem is that void* is presumably pointing to the start of the derived object, whereas you need a pointer to the base class sub-object from which the cast-to type derives.)


dynamic_cast works only on polymorphic types, i.e. classes containing virtual functions.

In gcc you can dynamic_cast to void* but not from:

struct S
{
    virtual ~S() {}
};

int main()
{
    S* p = new S();
    void* v = dynamic_cast<void*>(p);
    S* p1 = dynamic_cast<S*>(v); // gives an error
}