Encapsulation - Kamills-12/2143-OOP GitHub Wiki
Encapsulation is basically: keep your stuff private unless someone really needs to use it.
It means wrapping up your data (variables) and functions (methods) into one class, and protecting parts of it so nothing outside the class messes with it directly.
- You stop random code from changing important stuff.
- You make sure everything goes through the user.
- Easier to debug because changes are controlled.
#include <iostream>
using namespace std;
class BankAccount {
private:
double balance; // nobody can touch this directly
public:
void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
double getBalance() {
return balance;
}
};
int main() {
BankAccount myAccount;
myAccount.deposit(500);
cout << "Balance: $" << myAccount.getBalance() << endl;
// myAccount.balance = 1000000; nah, can't do that
return 0;
}