Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

void pointer to a dynamically allocated class

I'm trying to pass a void* to a function, then inside that function make the pointer point to an dynamically created object. This is what I have so far but it doesn't seem to be working:

main:

int main()
{
  void* objPtr;

  setPtr(objPtr);
}

setPtr:

void setPtr(void*& objPtr)
{
  objPtr = new Obj1; 
  (*objPtr).member1 = 10; //error: expression must have pointer-to-class type
}

Obj1:

struct Obj1
{
  int member1;
};

Thanks in advance

like image 720
Logan Besecker Avatar asked Dec 04 '25 13:12

Logan Besecker


1 Answers

Well, sure: a void* doesn't point to a class type, so can't be used to access members. C++ is statically typed. The compiler sees a void* and that's that. It won't try to figure out what type of object the pointer actually points to -- you have to tell it, with a cast:

objPtr->whatever; // fails: objPtr is not a pointer-to-class-type

((actual_type*)objPtr)->whatever; // okay: cast to actual_type*

Well, that's the C programmer in me. Some folks prefer to use static_cast here:

static_cast<actual_type*>(objPtr)->whatever; // okay: cast to actual_type*

However you do it, though, you have to be sure that objPtr in fact points to an object of type actual_type.

like image 73
Pete Becker Avatar answered Dec 06 '25 03:12

Pete Becker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!