C++ programming 3 min read

Classes and objects

A class bundles data with the functions that use it, and each object is one instance with its own data. A constructor sets an object up the moment it is created, which in firmware can mean configuring a pin.

class Led declares the data int pin_ and bool on_ and the functions on() and off(). Two objects are created from it: Led red{5} with pin_ 5 and Led green{6} with pin_ 6, each with its own copy of the data.
One class, many objects, each with its own data.

Data and functions together

led.cppC++
#include <iostream>class Led {public:    explicit Led(int pin) : pin_(pin) {        std::cout << "pin " << pin_ << " configured as output\n";    }    void on() {        on_ = true;        std::cout << "pin " << pin_ << " on\n";    }    bool is_on() const { return on_; }private:    int pin_;    bool on_ = false;};int main() {    Led red{5};    Led green{6};    red.on();    std::cout << "green is " << (green.is_on() ? "on" : "off") << '\n';}
Output
pin 5 configured as output
pin 6 configured as output
pin 5 on
green is off

Constructors set things up

The constructor runs as soon as the object exists, so a pin is never left half-configured. The : pin_(pin) part, the member initializer list, sets members before the body runs. Pair setup in the constructor with clean-up in a destructor, ~Led(), and you get RAII: resources are tied to the object’s lifetime.