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 in C++ can be used to perform type safe down casting. dynamic_cast is run time polymorphism. The dynamic_cast operator, which safely converts from a pointer (or reference) to a base type to a pointer (or reference) to a derived type.
The primary purpose for the dynamic_cast operator is to perform type-safe downcasts. A downcast is the conversion of a pointer or reference to a class A to a pointer or reference to a class B , where class A is a base class of B .
Yes, dynamic_cast is a code smell, but so is adding functions that try to make it look like you have a good polymorphic interface but are actually equal to a dynamic_cast i.e. stuff like can_put_on_board .
If the cast is successful, dynamic_cast returns a value of type new-type. If the cast fails and new-type is a pointer type, it returns a null pointer of that type. If the cast fails and new-type is a reference type, it throws an exception that matches a handler of type std::bad_cast.
dynamic_cast Operator. Converts the operand expression to an object of type type-id. Syntax. Remarks. The type-id must be a pointer or a reference to a previously defined class type or a "pointer to void". The type of expression must be a pointer if type-id is a pointer, or an l-value if type-id is a reference.
If the cast fails and new-type is a pointer type, it returns a null pointer of that type. If the cast fails and new-type is a reference type, it throws an exception that matches a handler of type std::bad_cast . Only the following conversions can be done with dynamic_cast, except when such conversions would cast away constness or volatility .
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.
The “ dynamic_cast ” performs a run-time type casting which also checks the type casting validity. If type casting is done to compatible type then it succeeds else it will throw “ bad_cast ” exception.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With