Labs ICT
โญ Pro Login

Encapsulation

Encapsulation

Encapsulation hides internal data and only exposes what is necessary. Mark data members as private and provide public getter/setter functions.

Why Encapsulation?

It protects an object's integrity by preventing external code from directly modifying internal state. Validation logic can be placed inside setters.

#include <iostream>
using namespace std;

class BankAccount {
private:
  double balance;

public:
  BankAccount() {
    balance = 0;
  }

  double getBalance() {
    return balance;
  }

  void deposit(double amount) {
    if (amount > 0)
      balance += amount;
  }

  void withdraw(double amount) {
    if (amount > 0 && amount <= balance)
      balance -= amount;
  }
};

int main() {
  BankAccount acc;
  acc.deposit(500);
  acc.withdraw(100);
  cout << "Balance: " << acc.getBalance() << "\n";
  return 0;
}
Try it Yourself โ†’

๐Ÿงช Quick Quiz

What access modifier makes members accessible only within the class?