Encapsulation means hiding your data to keep it safe. In C++, we make data private and we only allow access through public functions.
Think of it like a bank locker. Your money is inside the locker (private). You cannot touch it directly. You have to use a key (public function) to open it. This keeps your money safe.
Let's see a simple example:
cpp
#include <iostream>
using namespace std;
class BankAccount {
private:
int balance = 1000;
public:
void showBalance() {
cout << "Your balance is: " << balance << endl;
}
void deposit(int amount) {
balance = balance + amount;
cout << "Deposited: " << amount << endl;
}
};
int main() {
BankAccount myAccount;
myAccount.showBalance();
myAccount.deposit(500);
myAccount.showBalance();
return 0;
}
Your balance is: 1000
Deposited: 500
Your balance is: 1500
Top comments (0)