How to cast a pointer to void object to class object?
With a static_cast
. Note that you must only do this if the pointer really does point to an object of the specified type; that is, the value of the pointer to void
was taken from a pointer to such an object.
thing * p = whatever(); // pointer to object void * pv = p; // pointer to void thing * p2 = static_cast<thing *>(pv); // pointer to the same object
If you find yourself needing to do this, you may want to rethink your design. You're giving up type safety, making it easy to write invalid code:
something_else * q = static_cast<something_else *>(pv); q->do_something(); // BOOM! undefined behaviour.
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