Log in

View Full Version : void* pointer to object in C++


byteit101
14-01-2009, 15:43
I have been at this for some time now, and this won't compile:
(function(int data))
void * MyPointer
if (data=0)
{
Gyro gy(1);
MyPointer = &gy;
}
if (data=1)
{
Ultrasonic gy(1);
MyPointer = &gy;
}
if (etc...
etc...
(function2(int data2))
if (data2=0)
return MyPointer->GetValue(); //this produces error: 'void*' is not a pointer-to-object type (:eek:)
etc...

You can probably see what i am doing, (accessing different function based on sensor type), and Nothing has worked :(

virtuald
14-01-2009, 15:51
Don't use a void pointer, use a pointer to the base class. So for those I think its SensorBase.

jee7s
14-01-2009, 15:58
To be in line with the strictest and most proper C++ design principles (a very good idea), you don't want to use void* in the scenario you describe. Rather, you want to take advantage of polymorphism and use an abstract base class pointer instead.

For example, if all your sensors derive from a single abstract base class (like the WPILib classes do), then you can use a pointer to the base class to access the inherited class functions.

I assume that GetValue is inherited from SensorBase and is virtual. ( I don't have the library in front of me at the moment.) Therefore, rather than using a void* you can use a SensorBase* like this:

Gyro gy(1);
Ultrasound us(2);
SensorBase* mySensor;
mySensor = &gy;
mySensor->GetValue(); //mySensor calls Gyro::GetValue() here
mySensor = &us;
mySensor->GetValue();//mySensor calls Ultrasound::GetValue() here

If you want to use the void* you need to recast it for the compiler to know what you are doing. So, you need a recast for each different sensor. This leads to all sorts of extra code that you avoid by going the polymorphic route.

-Jeff Erickson, FRC 41

byteit101
14-01-2009, 15:59
Thanks! I'll Try that!

slavik262
14-01-2009, 16:28
And for future reference, void pointers need to be casted to the correct pointer type in order to be used. This should fix your error.

byteit101
14-01-2009, 16:41
like (Gyro)MyPointer->GetValue();?
or ((Gyro)MyPointer)->GetValue();?
or ((Gyro)(*MyPointer))->GetValue();?

heydowns
14-01-2009, 17:15
like (Gyro)MyPointer->GetValue();?
or ((Gyro)MyPointer)->GetValue();?
or ((Gyro)(*MyPointer))->GetValue();?

None of the above.
Your pointer is the wrong type. So it's the pointer you have to cast to the correct type of pointer:

((Gyro *)MyPointer)->GetValue()

But you don't want to do this :) Do as suggested in the prior posts as it is much cleaner and less error-prone.