View Full Version : void* pointer to object in C++
byteit101
01-14-2009, 03:43 PM
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
01-14-2009, 03:51 PM
Don't use a void pointer, use a pointer to the base class. So for those I think its SensorBase.
jee7s
01-14-2009, 03:58 PM
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
01-14-2009, 03:59 PM
Thanks! I'll Try that!
slavik262
01-14-2009, 04:28 PM
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
01-14-2009, 04:41 PM
like (Gyro)MyPointer->GetValue();?
or ((Gyro)MyPointer)->GetValue();?
or ((Gyro)(*MyPointer))->GetValue();?
heydowns
01-14-2009, 05:15 PM
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.
vBulletin® v3.6.4, Copyright ©2000-2009, Jelsoft Enterprises Ltd.