Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 989
Naveen Avatar asked Apr 09 '12 10:04

Naveen


1 Answers

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. 
like image 114
Mike Seymour Avatar answered Sep 19 '22 13:09

Mike Seymour