33. Abstract Sensor Debugging

#include <iostream>
using namespace std;

class Sensor {
public:
    virtual int readValue() const = 0;
    virtual ~Sensor() = default;
};

class TemperatureSensor : public Sensor {
private:
    int temperature;
public:
    TemperatureSensor(int t) : temperature(t) {}
    int readValue() const override { return temperature; } // fixed
};
 
int main() {
    int t;
    cin >> t;

    TemperatureSensor ts(t);
    Sensor* ptr = &ts;

    cout << "Temperature=" << ptr->readValue();
    return 0;
}

Solution Details

  • The base class Sensor declares readValue() as pure virtual, which makes it abstract.
     
  • An abstract class cannot be instantiated. Any class that inherits it must provide an implementation of readValue().
     
  • Adding the missing function in TemperatureSensor makes it a concrete class, so the code compiles and runs.

👉 In simple words: The base class (Sensor) sets a rule: “every sensor must say its value.” If the derived class (TemperatureSensor) doesn’t follow the rule, the compiler refuses to build the code.
 

Significance for Embedded Developers

  • Abstract classes define driver interfaces in firmware.
  • Each hardware driver must implement the required functions, or it won’t compile.
  • This ensures all drivers follow the same rules, making firmware modular and consistent.
     
Loading...

Input

25

Expected Output

Temperature=25