Using a void parameter

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class SpecialObject {
  public:
    int compare(const SpecialObject *);
 ... 
};

int sort_special_object(void* element1, void* element2) {
   SpecialObject* obj1 = (SpecialObject*)element1;
   SpecialObject* obj2 = (SpecialObject*)element2;

   return (obj1.compare(obj2));
}

int sort_integer(void* element1, void* element2) {
   int obj1 = (int*)element1;
   int obj2 = (int*)element2;
   return (*obj1 <= *obj2);
}

...

Topic archived. No new replies allowed.