C++ typecast: cast a pointer from void pointer to class pointer

Naveen picture Naveen · Apr 9, 2012 · Viewed 31.7k times · Source

How to cast a pointer to void object to class object?

Answer

Mike Seymour picture Mike Seymour · Apr 9, 2012

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.