So, the library I'm using uses an abstract class, for which I'm supposed to define certain functions with my own code and pass an instance of my derived class to another function. But the last parameter of the virtual function I need to define is this:
void *userData
The documentation says that I can pass any type into the function, and indeed I can pass one of my own classes in. But when I try to use userData, I get the compile error needs class type. So how do I access it?
void pointers need to be cast back to whatever type they were originally. You can do this with just a normal pointer typecast:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
void func(void* ptr)
{
int* p = (int*)ptr; // cast it to an int
// now we can use it as an int*
*p = 5;
}
int main()
{
int v = 0;
func(&v);
cout << v; // prints 5
}
Disch's answer is probably going to be the best for you.
A good example of this is qsort where it expects the format to be int your_function_name(void* element1, void* element2) { ... }
Since you know the types of data you'll be passing in, you'll also have the opportunity to customize it, and for that, you need to cast the void* to your element type.