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 avoid*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:Well, that’s the C programmer in me. Some folks prefer to use
static_casthere:However you do it, though, you have to be sure that
objPtrin fact points to an object of typeactual_type.