C++ programming 2 min read

public, private, protected

Access specifiers decide who may touch a member. Keep data private and expose a small public interface, so the rest of the firmware can’t put the hardware into an invalid state.

public members can be used inside the class, in derived classes and by other code. protected members inside the class and in derived classes only. private members only inside the class.
Who can use public, protected and private members.

A safe interface

Here the duty cycle can only change through set_duty(), which keeps it between 0 and 100. Code outside the class can’t write duty_ directly.

pwm.cppC++
#include <iostream>class PwmChannel {public:    void set_duty(int percent) {        if (percent < 0) percent = 0;        if (percent > 100) percent = 100;        duty_ = percent;    }    int duty() const { return duty_; }private:    int duty_ = 0;   // only PwmChannel may write this};int main() {    PwmChannel fan;    fan.set_duty(140);      // clamped to 100    // fan.duty_ = 140;     // error: 'duty_' is private    std::cout << "duty: " << fan.duty() << "%\n";}
Output
duty: 100%

protected

protected sits in between: derived classes can use the member, other code can’t. It is useful in a base class that its subclasses build on, as in the next insight.