C++ programming 2 min read

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.

class Sensor declares virtual int read() = 0. Temperature and Light derive from it and override read(). An object such as Temperature t holds a hidden vptr pointing to the vtable for Temperature, whose entry read points to Temperature::read; a call through a Sensor pointer looks the function up there.
Derived classes share the Sensor interface; virtual calls go through the vtable.

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.