Encapsulation
So far, every member was under public:, so any line of the program could change it to any value. Think of a thermostat object with a target temperature. Nothing stops some code from setting it to 5000 degrees. Encapsulation fixes this. You hide the data, and you let the rest of the program change it only through methods that check the rules.
#include <iostream>
using namespace std;
class Thermostat {
private:
int target = 20;
public:
void setTarget(int degrees) {
if (degrees >= 5 && degrees <= 30) {
target = degrees;
}
}
int getTarget() {
return target;
}
};
int main() {
Thermostat living;
living.setTarget(24);
cout << living.getTarget() << "\n";
living.setTarget(300);
cout << living.getTarget() << "\n";
return 0;
}
Output:
24
24
private: means that only the class's own methods can use target. Code outside the class, like main, must go through the public methods.
setTarget(24) was inside the allowed range of 5 to 30, so target became 24. setTarget(300) was outside the range, so the method did nothing, and target stayed 24.
If main tries to change target directly, the program does not compile:
#include <iostream>
using namespace std;
class Thermostat {
private:
int target = 20;
public:
int getTarget() {
return target;
}
};
int main() {
Thermostat living;
living.target = 300;
return 0;
}
Output:
main.cpp: In function ‘int main()’:
main.cpp:16:12: error: ‘int Thermostat::target’ is private within this context
The mistake is caught before the program runs, at line 16. A wrong value can never get in.
Getters and setters
A method that reads a private member is called a getter, like getTarget. A method that changes it is called a setter, like setTarget. A setter is the right place to check the new value.
You do not need a getter and a setter for every member. If a setter only copies the value without checking anything, the member might as well be public. Some members need only a getter, so the rest of the program can read them but never change them.
class and struct
In a class, members are private unless you write public:. In a struct, members are public unless you write private:. That is the main difference between them: a struct can have methods too. Most programmers use a struct for simple groups of data, and a class when there are rules to protect.
In the exercise, the balance of a bank account is private. Finish the methods that add money and take it out, so the balance can never go below zero.