lundi 15 octobre 2018

Changing the base class of an Object dynamically in C++

I have two classes Sensor1 & Sensor2 which inherits from class Sensor. I am creating class Camera for which the base class should be Sensor1 or Sensor2 based on some condition in the run-time. Is it possible?

One way is to create a pointer member for Sensor in Camera and then assign to Sensor1 or Sensor2 (based on condition) and in that case for all the methods of Sensor, I need to create the methods in Camera (setResolution & changeMode) and call the corresponding methods (which I want to avoid)

class Sensor {
 public:
       Sensor(){}
       ~Sensor(){}
       void setResolution(int w, int h) {};
       void changeMode(int mode) {};
}

class Sensor1: public Sensor {
  public:
       Sensor1(){}
       ~Sensor1(){}
       void setResolution(int w, int h) {\** change based on sensor **\}
       void changeMode(int mode) {\** sensor specific implementation **\}
}

class Sensor2: public Sensor {
   public:
       Sensor2(){}
       ~Sensor2(){}
       void setResolution(int w, int h) {\** change based on sensor **\}
       void changeMode(int mode) {\** sensor specific implementation **\}

class Camera: public Sensor {
   public:
       Camera (bool flag){
       //Change base class to either Sensor1 or Sensor2 which inherits from common base class Sensor
       }
       ~Camera(){}
}

Aucun commentaire:

Enregistrer un commentaire