how can I convert any object of my own class convert into pointer to void?
MyClass obj;
(void*)obj; // Fail
The void pointer in C is a pointer that is not associated with any data types. It points to some data location in the storage. This means that it points to the address of variables. It is also called the general purpose pointer. In C, malloc() and calloc() functions return void * or generic pointers.
Void functions are created and used just like value-returning functions except they do not return a value after the function executes. In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value.
void pointer in C / C++ A void pointer is a pointer that has no associated data type with it. A void pointer can hold address of any type and can be typecasted to any type.
Any type of pointer can be assigned to (or compared with) a void pointer, without casting the pointer explicitly. Finally, a function call can be cast to void in order to explicitly discard a return value. For example, printf returns a value, but it is seldom used.
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.
You cant convert a non-pointer to void*
. You need to convert the pointer to your object to void*
(void*)(&obj); //no need to cast explicitly.
that conversion is implicit
void* p = &obj; //OK
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