C++ Programming: Objects, RAII and the STL ยท Classes and Objects
Keep data private and change it only through methods that check the rules.
#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;
}home is created on the stack with the value {target: 20}.t >= 10 && t <= 30 to decide which way the code goes.home changes from {target: 20} to {target: 24}.set() has finished, so its variables are gone.t >= 10 && t <= 30 to decide which way the code goes.set() has finished, so its variables are gone.get(). It gets its own variables on the stack.get() has finished, so its variables are gone. It prints 24.cout << home.get() << endl.0.