I need to convert an integral type which contains an address to the actual pointer type. I could use reinterpret_cast as follows:
MyClass *mc1 = reinterpret_cast<MyClass*>(the_integer);
However, this does not perform any run-time checks to see if the address in question actually holds a MyClass object. I want to know if there is any benefit in first converting to a void* (using reinterpret_cast) and then using dynamic_cast on the result. Like this:
void *p = reinterpret_cast<void*>(the_integer);
MyClass *mc1 = dynamic_cast<MyClass*>(p);
assert(mc1 != NULL);
Is there any advantage in using the second method?
Type checking on
dynamic_castis implemented in different ways by different C++ implementations; if you want an answer for your specific implementation you should mention what implementation you are using. The only way to answer the question in general is to refer to ISO standard C++.By my reading of the standard, calling
dynamic_caston a void pointer is illegal:(from 5.2.7.2 of the ISO C++ standard).
voidis not a complete class type, so the expression is illegal.Interestingly, the type being cast to is allowed to be a void pointer, i.e.
In this case, the
dynamic_castalways succeeds, and the resultant value is a pointer to the most-derived object pointed to byv.