Inheritance
Inheritance lets several classes share one interface. Code written against a base class works with any derived class, and virtual functions pick the right implementation at run time, at the cost of a small table lookup.
One interface, many sensors
sensor.cppC++
#include <iostream>class Sensor {public: virtual ~Sensor() = default; virtual int read() = 0; // every sensor must provide read()};class Temperature : public Sensor {public: int read() override { return 23; }};class Light : public Sensor {public: int read() override { return 870; }};void report(Sensor& s) { std::cout << "reading: " << s.read() << '\n';}int main() { Temperature t; Light l; report(t); report(l);}
Output
reading: 23 reading: 870
What virtual costs
Each object of a class with virtual functions carries a hidden pointer to its class’s vtable, and a virtual call reads the table entry before jumping. On a Cortex-M that is a few extra cycles and one pointer per object: usually fine, but worth avoiding in the tightest interrupt code.