Menu

Encapsulation in C++ - Explained in Simple Words
📰

Encapsulation in C++ - Explained in Simple Words

DEV Community: cpp·Aliza Kanwal·4 days ago
#QSzOXrnb
#devtocpp#devto#dev#include#balance
Reading 0:00
15s threshold
Cover image for Encapsulation in C++ - Explained in Simple Words

Aliza Kanwal

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

Enter fullscreen mode Exit fullscreen mode