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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With