Search code examples
c++pointerscastingvoid

Convert into void*


how can I convert any object of my own class convert into pointer to void?

MyClass obj;
(void*)obj; // Fail

Solution

  • MyClass obj;
    void *p;
    
    p = (void*)&obj; // Explicit cast.
    // or:
    p = &obj; // Implicit cast, as every pointer is compatible with void *
    

    But beware ! obj is allocated on the stack this way, as soon as you leave the function the pointer becomes invalid.

    Edit: Updated to show that in this case an explicit cast is not necessary since every pointer is compatible with a void pointer.