Skip to content
UPEEC

Abstract Classes

A class with at least one pure virtual function — an interface that can't be instantiated.

Intermediate
Comments 0
class Sensor {
public:
    virtual float read() = 0;     // "= 0" makes it pure virtual
    virtual ~Sensor() = default;
};

class Dht22 : public Sensor {
public:
    float read() override { /* talk to the sensor */ return 24.0f; }
};

Code written against Sensor& works with any sensor — easy to swap hardware or use a fake sensor in tests.

Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.

Discussion (0)

Sign in or join free to ask questions and discuss this topic.