According to this, void*
has no RTTI information, therefore casting from void*
is not legal and it make sense.
If I remember correctly, dynamic_cast
from void*
was working on gcc.
Can you please clarify the issue.
According to this, void*
has no RTTI information, therefore casting from void*
is not legal and it make sense.
If I remember correctly, dynamic_cast
from void*
was working on gcc.
Can you please clarify the issue.
dynamic_cast
works only on polymorphic types, i.e. classes containing virtual functions.In gcc you can
dynamic_cast
tovoid*
but not from:It is true that
void*
can't bedynamically_cast
ed from.You are probably mis-remembering. With g++ 4.5 and the following code
I get the following error:
You can cast a pointer to polymorphic type to
void *
, but not vice versa.In
5.2.7 - Dynamic cast [expr.dynamic.cast]
it says that fordynamic_cast<T>(v)
:T
is a pointer type,v
shall be an rvalue of a pointer to complete class typeT
is a reference type,v
shall be an lvalue of a complete class type (thanks usta for commenting on my missing this)...
v
shall be a pointer to or an lvalue of a polymorphic typeSo, 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 codedynamic_cast
-ing only knows it's avoid*
. Let's say you're trying to cast it to aDerived2*
, where both derived classes have a common base. Superficially, you might think all the pointers would point to the sameBase
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 neededBase
class sub-object might not be the one to which theDerived*
- available only as avoid*
- 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.(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 thatvoid*
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.)I guess you confuse with
dynamic_cast
tovoid*
. That is legal and obtains the pointer to the most derived class object.dynamic_cast
fromvoid*
is illegal - the type casted from must be polymorphic - contain at least one virtual function (virtual destructor counts too).