So I was reading the answers to dynamic_cast from "void *" and although you can’t cast from a void * to a T * several of the responses point out that it is possible to cast a T * to a void *, but don’t give any indication why you’d want to do that.
Is this just a bit of trivia that it’s possible, or is there a case where it would make sense? I thought about maybe for readability or to make it clear that we’re converting to a void *, but given the purpose of dynamic_cast, it doesn’t fit very well to me.
For that matter, is there any reason to do anything other than let T * become void * implicitly? I’ve seen C-style casts to void * used from time to time for this purpose, I presume just to be explicit (assuming we’re not doing something unusual like casting int to a pointer or something).
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 ofxis polymorphic.This can be useful in a handful of scenarios, where the address serves as object identity:
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.