I have a C++ program:
struct arguments
{
int a, b, c;
arguments(): a(3), b(6), c(9) {}
};
class test_class{
public:
void *member_func(void *args){
arguments vars = (arguments *) (*args); //error: void is not a
//pointer-to-object type
std::cout << "\n" << vars.a << "\t" << vars.b << "\t" << vars.c << "\n";
}
};
On compile it throws an error:
error: ‘void*’ is not a pointer-to-object type
Can someone explain what I am doing wrong to produce this error?
You are dereferencing the
void *
before casting it to a concrete type. You need to do it the other way around:This order is important, because the compiler doesn't know how to apply
*
toargs
(which is avoid *
and can't be dereferenced). Your(arguments *)
tells it what to do, but it's too late, because the dereference has already occurred.*args means "the object(value) args points to". Therefore, it can not be casted as pointer to object(argument). That's why it is giving error
The problem as bdonlan said is "dereferencing
void*
before casting".I think this example would help:
Bare bones example to reproduce the above error:
The above code is wrong because it is trying to dereference a pointer to a void. That's not allowed.
Now run the next code below, If you understand why the following code runs and the above code does not, you will be better equipped to understand what is going on under the hood.
You have the
*
in the wrong place. So you're trying dereference thevoid*
. Try this instead:Alternatively, you can do this: (which also avoids the copy-constructor - as mentioned in the comments)