C++ Programming: Objects, RAII and the STL ยท Classes and Objects

Encapsulation: private and public

Keep data private and change it only through methods that check the rules.

encapsulation.cpp

#include <iostream>
using namespace std;

class Thermostat {
private:
    int target = 20;
public:
    int get() const { return target; }

    void set(int t) {
        if (t >= 10 && t <= 30) {
            target = t;
        }
    }
};

int main() {
    Thermostat home;
    home.set(24);
    home.set(99);           // rejected: out of range
    cout << home.get() << endl;
    return 0;
}

Step by step

  1. home is created on the stack with the value {target: 20}.
  2. set(24): inside the allowed range.
  3. C++ checks t >= 10 && t <= 30 to decide which way the code goes.
  4. home changes from {target: 20} to {target: 24}.
  5. set() has finished, so its variables are gone.
  6. set(99) is outside 10 to 30.
  7. C++ checks t >= 10 && t <= 30 to decide which way the code goes.
  8. set() has finished, so its variables are gone.
  9. C++ calls get(). It gets its own variables on the stack.
  10. get() has finished, so its variables are gone. It prints 24.
  11. Line runs: cout << home.get() << endl.
  12. The method returns 0.
  13. 24.