Why would I use dynamic_cast to cast TO a void *?

There is a purpose to this, kinda. It is hinted at in the part of the spec that allows it. From N3337, section 5.2.7, paragraph 7:

If T is “pointer to cv void,” then the result is a pointer to the most derived object pointed to by v.

So a dynamic_cast<void*>(...) is really shorthand for static_cast<void*>(dynamic_cast<MostDerivedType*>(...)). And that would be useful... sort of.

The difficulty in making it useful is that you don't necessarily know what MostDerivedType is. After all, it can be different for each expression. So once you have it as a void*, you don't necessarily have a way to cast it back safely. If you make a guess about MostDerivedType and just static_cast it, and you're wrong, then you're in undefined behavior land. Whereas if you do the dynamic_cast to that type (then static_cast to void*), it will at least return NULL if it isn't of that type.

So no, I would say that it isn't very useful. Not if you want to live within the boundaries of C++ and not rely on potentially undefined behavior.


First, when using dynamic_cast<void*>(x) you get a pointer to the first byte of the most derived object. As long as the static type of x is polymorphic.

This can be useful in a handful of scenarios, where the address serves as object identity:

  • you now have a way to fully distinguish pointers to subobjects of the same object from pointers to unrelated subobjects.
  • you can now walk some twisted graphs without visiting the same object several times... which can be used for serialization.

Granted, this is certainly not a daily usage, but in C++ the memory address is a de-facto identifier for objects, so a mechanism to access it from any part of the inheritance hierarchy certainly is useful for those few edge cases.

Tags:

C++

Casting