124. Abstract Sensor Debugging

#include <iostream>
using namespace std;

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

// Concrete sensor implementation
class TemperatureSensor : public Sensor {
private:
    int temperature;
public:
    TemperatureSensor(int t) : temperature(t) {}
    int readValue() const override {
        return temperature;
    }
};

int main() {
    int t;
    cin >> t;

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

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

Explanation & Logic Summary:

The Sensor base class defines a pure virtual function, making it an abstract interface.
Any concrete sensor class must implement this function to be instantiable.

In the template code, TemperatureSensor does not implement readValue(), so the compiler rejects the program.
By adding the missing method with the correct signature, the class fully satisfies the interface contract.

This allows the object to be accessed safely through a base-class pointer and enables polymorphic behavior without runtime checks.

Firmware Relevance & Real-World Context:

In embedded firmware, abstract base classes are widely used to define hardware driver interfaces such as sensors, peripherals, and communication modules.

Compile-time enforcement ensures that:

  • Incomplete drivers cannot be integrated
  • Interface contracts are always honored
  • Errors are detected early during the build process

This pattern improves firmware reliability, maintainability, and architectural correctness—especially in safety-critical or resource-constrained systems.

 

 

 

 

Loading...

Input

25

Expected Output

Temperature=25