C++ classes and OOP for embedded
Classes, constructors, inheritance, virtual calls and what they cost.
Why C++ on a microcontroller
C++ compiles to the same machine code as C when you use the same ideas. What it adds is a way to say those ideas in the language instead of in comments: a driver owns its peripheral, a buffer cannot be copied, a pin must be configured before use. Most of the features below cost nothing at run time. The few that do cost something are worth knowing exactly.
| Feature | Run-time cost |
|---|---|
| Classes, member functions, access control | None: a member function is a function with a hidden this pointer |
| Constructors and destructors | Only the code you write in them |
| Non-virtual inheritance | None |
| Virtual functions | One pointer per object (the vtable pointer), one table per class in flash, an indirect call |
| Templates | None at run time; possibly more flash if instantiated for many types |
| Exceptions, RTTI | Significant flash and unpredictable timing; usually disabled |
A class is a struct with rules
class Led {
public:
Led(GpioPort &port, uint8_t pin) : port_(port), pin_(pin) {
port_.set_output(pin_);
}
void on() { port_.set(pin_); }
void off() { port_.clear(pin_); }
void toggle() { port_.toggle(pin_); }
private:
GpioPort &port_;
uint8_t pin_;
};
This is exactly the C pattern of a struct plus functions that take a pointer to it:
#include <stdio.h>
#include <stdint.h>
typedef struct { uint32_t odr; } gpio_port_t;
typedef struct { gpio_port_t *port; uint8_t pin; } led_t;
static void led_init(led_t *self, gpio_port_t *port, uint8_t pin) { self->port = port; self->pin = pin; }
static void led_on(led_t *self) { self->port->odr |= (1u << self->pin); }
static void led_toggle(led_t *self) { self->port->odr ^= (1u << self->pin); }
int main(void) {
gpio_port_t porta = { 0 };
led_t status;
led_init(&status, &porta, 5); // the C++ constructor
led_on(&status); // status.on()
printf("ODR = 0x%02X\n", (unsigned)porta.odr);
led_toggle(&status); // status.toggle()
printf("ODR = 0x%02X\n", (unsigned)porta.odr);
return 0;
}
The C++ version gains three things for free: the constructor cannot be forgotten, private stops other code reaching into pin_, and the calls read naturally.
Constructors, destructors and static objects
A global object's constructor runs before main, called from the startup code (the __libc_init_array / .init_array step). Two consequences matter on hardware:
- Clocks may not be on yet. A global
Uart debug(USART2);whose constructor writes registers can run before the clock tree is configured. Keep constructors to plain field assignment, and do hardware setup in an explicitinit()called frommain. - Initialisation order across files is unspecified. One global must not depend on another global in a different file being constructed first (the "static initialisation order fiasco"). A function-local
staticis constructed on first use, which avoids the problem, but adds a guard variable and, with threads, a lock.
Destructors of global objects almost never run in firmware because main never returns. Destructors of local objects run at the end of their scope, which is what makes RAII useful.
Inheritance and virtual functions
Use virtual functions when the same code must work with different implementations chosen at run time: several sensor types behind one interface, or a real driver and a fake for tests.
class TempSensor {
public:
virtual int read_centi_celsius() = 0; // pure virtual: an interface
virtual ~TempSensor() = default;
};
class Tmp117 : public TempSensor {
public:
int read_centi_celsius() override { /* I2C transaction */ return 2150; }
};
void log_temperature(TempSensor &s) { printf("%d\n", s.read_centi_celsius()); }
Each object with virtual functions carries a hidden pointer to its class's vtable, a table of function pointers in flash. A virtual call loads that pointer, loads the entry and calls through it. It is the same as the C dispatch table you would write by hand, and costs a few cycles plus the lost chance to inline.
Pitfall: If a base class has virtual functions and objects are ever destroyed through a base pointer, the destructor must be virtual. In firmware without
deletethis rarely bites, but= defaultcosts nothing, so write it.
Static polymorphism with CRTP
When the implementation is known at compile time, the curiously recurring template pattern gives an interface with no vtable and full inlining:
template <typename Derived>
class SensorBase {
public:
int read() { return static_cast<Derived *>(this)->read_raw() * 10; }
};
class Ntc : public SensorBase<Ntc> {
public:
int read_raw() { return 215; }
};
Ntc{}.read() compiles to a constant. The cost is that each SensorBase<X> is a separate type, so you cannot keep a mixed array of them.
Copying hardware
A class that owns a peripheral should not be copyable: two objects both believing they own UART2 is a bug. Delete the copy operations:
class Uart {
public:
explicit Uart(USART_TypeDef *regs);
Uart(const Uart &) = delete;
Uart &operator=(const Uart &) = delete;
};
explicit on single-argument constructors stops accidental conversions, another habit worth keeping.
Interview question: Why is it risky to configure hardware in the constructor of a global C++ object?
Answer: Global constructors run from the startup code before main, often before the clock tree, power domains or the peripheral clock enables have been set up, so the register writes may be ignored or fault. Their order across translation units is also unspecified. The safe pattern is a trivial constructor that only stores parameters, plus an explicit init() called from main in a known order.
Interview question: When would you choose virtual functions over templates (CRTP) for a driver interface?
Answer: Virtual functions when the implementation is chosen at run time or objects of different types must sit in one container, for example a list of sensors read in a loop, or swapping a real driver for a mock in tests without recompiling the caller. Templates when the type is fixed at compile time and you want inlining and no vtable, such as a GPIO pin class used in a hot loop. The cost of virtual is small (a pointer per object and an indirect call) but it blocks inlining.
Going deeper
Interview question: How would you model a robot vacuum's hardware in C++ so parts can be swapped?
Answer: Define small interfaces for each role (a drive, a bumper sensor, a brush motor), implement them for each hardware variant, and have the navigation code depend only on the interfaces, wired up at start-up with no heap. Static polymorphism (templates) avoids virtual calls where speed matters. Each class can then be tested with a fake on a PC.
Interview question: What is the static initialisation order problem and how do you avoid it?
Answer: Global objects in different source files are constructed before main in an unspecified order, so a global whose constructor uses another file's global may use it before it is constructed. Avoid it by keeping constructors trivial and initialising explicitly from main in a known order, or by using a function-local static (constructed on first use), accepting its small guard cost.
Interview question: Why should a class that owns hardware delete its copy constructor?
Answer: Copying it would create two objects that both believe they own the same peripheral, each configuring and driving it, and possibly both releasing it in their destructors. Deleting the copy constructor and copy assignment makes such copies a compile error; ownership can still be transferred explicitly with a move if that makes sense.
Explain it: In your own words, explain what a virtual function costs at run time and when it is worth it.
Answer: Each object of a class with virtual functions holds a hidden pointer to its class's vtable, a table of function pointers in flash, so it costs one pointer per object. A virtual call loads that pointer, loads the right entry and calls through it, a few cycles more than a direct call, and it prevents the compiler from inlining. It is worth it when the implementation is chosen at run time or different types must be handled through one interface, such as a list of different sensors or swapping a real driver for a test fake.