← C++ from Scratch Lesson 40 of 62 · 10 XP

Encapsulation: getters and setters

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

Encapsulation means hiding data and giving access to it through methods that follow the rules:

class Hero {
public:
    int hp() const { return hp_; }                 // a getter: read-only
    void setHp(int v) { hp_ = std::clamp(v, 0, maxHp_); }   // a setter: with a check (#include <algorithm>)
private:
    int hp_ = 100;
    int maxHp_ = 100;
};

The benefit: if the inner workings change later (say, the health becomes a double or is calculated from the armour), the code outside won't need rewriting — the interface stays the same.

Not every field needs a getter and a setter: if there are no rules, it's more honest to make a struct with public fields.

Task. A class Temperature stores a temperature in degrees Celsius, but not lower than −273.15. Methods: setCelsius(double) (below the limit, it sets the limit), celsius(), fahrenheit() (F = C × 9/5 + 32). Read n values; for each, print C F with one decimal place.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.