How to cast a pointer to void object to class object?
Asked
Active
Viewed 4.7k times
29
-
How did you get the pointer in the first place? How do you know it is really pointing at an object? How do you know what kind of object it is pointing at? – Karl Knechtel Apr 09 '12 at 12:06
1 Answers
42
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.

Mike Seymour
- 249,747
- 28
- 448
- 644
-
2@MarceloCantos: Why would you use an even more dangerous cast than the one you need? – Mike Seymour Apr 09 '12 at 10:45
-
3+1 @MarceloCantos: No, it is correct indeed. `static_cast` is used to reverse implicit conversions & class pointer to void pointer is an implicit conversion. – Alok Save Apr 09 '12 at 10:46
-
3OK, I'll take my lumps. I've always worked under the assumption that casting `void *` to `X *` should always use `reinterpret_cast` because that's what it was for. I stand corrected. – Marcelo Cantos Apr 09 '12 at 10:50
-
1`reinterpret_cast` is probably most commonly used to go from `X*` to `Y*`, where `X` and `Y` are both primitive types, typically making some machine-specific assumptions about memory layout. Even when you know the exact architecture it can be hard to avoid UB this way. – Karl Knechtel Apr 09 '12 at 12:08
-
4I don't understand the docs on this thing. If the void* cannot be cast to the class instance, will it return `nullptr` or broken pointer? – Tomáš Zato Apr 26 '17 at 12:15