-1

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?

ZyugyZarc
  • 15
  • 1
  • 4
  • 5
    Look up polymorphism. – NathanOliver Oct 21 '22 at 19:57
  • Whatever C++ book you are learning from, keep reading. Polymorphism should be covered in an early chapter. – Drew Dormann Oct 21 '22 at 20:16
  • Remember, by passing a parent pointer to a function, the function should only use the methods and members of the parent class. If you want the function to use child class methods or members, they should be moved up to the parent. Read up on "C++ slicing". – Thomas Matthews Oct 21 '22 at 20:55

1 Answers1

3

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Benoit
  • 76,634
  • 23
  • 210
  • 236