so here's a simplified version of my setup:
class GenericSensor{
public:
int read(){
return something;
}
};
class SpecialSensor : public GenericSensor{
public:
int read(){
return somethingElse;
}
};
and I have a function:
void someFunction(GenericSensor s){
printf("value is: %d\n", s.read());
}
how do I make someFunction
work with GenericSensor
, SpecialSensor
or any other derived class's object?
CodePudding user response:
You should declare read()
as a virtual
function which SpecialSensor
, or any other derived class, can override
.
Moreover, you should not pass GenericSensor
around by value, otherwise you will slice the caller's object. Rather, pass it around by pointer or reference instead. So have someFunction()
receive s
by GenericSensor*
pointer or GenericSensor&
reference.