Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++. Error: void is not a pointer-to-object type

Tags:

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?

like image 568
Matt Munson Avatar asked Oct 31 '11 03:10

Matt Munson


2 Answers

You are dereferencing the void * before casting it to a concrete type. You need to do it the other way around:

arguments vars = *(arguments *) (args);

This order is important, because the compiler doesn't know how to apply * to args (which is a void * and can't be dereferenced). Your (arguments *) tells it what to do, but it's too late, because the dereference has already occurred.

like image 59
bdonlan Avatar answered Oct 09 '22 01:10

bdonlan


Bare bones example to reproduce the above error:

#include <iostream>
using namespace std;
int main() {
  int myint = 9;             //good
  void *pointer_to_void;     //good
  pointer_to_void = &myint;  //good

  cout << *pointer_to_void;  //error: 'void*' is not a pointer-to-object type
}

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.

#include <iostream>
using namespace std;
int main() {
    int myint = 9;
    void *pointer_to_void;
    int *pointer_to_int; 
    pointer_to_void = &myint;
    pointer_to_int = (int *) pointer_to_void;

    cout << *pointer_to_int;   //prints '9'
    return 0;
}
like image 42
Eric Leschinski Avatar answered Oct 09 '22 02:10

Eric Leschinski