The problem with public data
If every member is public, anyone can put nonsense in it, like a bank balance of -1000000. The fix is encapsulation: hide the data (private) and only allow changes through methods that check the rules.
#include <iostream>
#include <string>
using namespace std;
class BankAccount {
private:
string owner;
double balance;
public:
BankAccount(string o) : owner(o), balance(0) {}
void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
bool withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
return true;
}
return false;
}
double getBalance() const {
return balance;
}
};
int main() {
BankAccount acc("Nina");
acc.deposit(100);
acc.deposit(-50); // ignored: not allowed
if (!acc.withdraw(500)) {
cout << "Not enough money\n";
}
acc.withdraw(30);
cout << "Balance: " << acc.getBalance() << "\n";
return 0;
}Output
Not enough money Balance: 70
Think of it like this: A bank account is like a cash machine. You can't open it and grab money directly (private). You use the buttons (public methods), and the machine checks the rules before it does anything.
Trying to touch private data from outside is stopped by the compiler:
#include <iostream>
using namespace std;
class Safe {
private:
int code = 1234;
};
int main() {
Safe s;
cout << s.code;
return 0;
}Output (the program does not compile)
main.cpp:11:15: error: 'code' is a private member of 'Safe'
cout << s.code;
^
main.cpp:6:9: note: declared private here
int code = 1234;
^Getters and setters
A getter returns a private value; a setter changes it, after checking it's valid:
#include <iostream>
using namespace std;
class Thermostat {
private:
int temperature = 20;
public:
int getTemperature() const { return temperature; }
void setTemperature(int t) {
if (t >= 10 && t <= 30) {
temperature = t;
} else {
cout << t << " is out of range\n";
}
}
};
int main() {
Thermostat t;
t.setTemperature(25);
t.setTemperature(99);
cout << "Now: " << t.getTemperature() << "\n";
return 0;
}Output
99 is out of range Now: 25
const methods
The const after getTemperature() promises that the method doesn't change the object. Mark every method that only reads data as const.
Remember: Good rule of thumb: make data
private, and make only the methods others needpublic.