Labs ICT
๐ŸŽ“ SIWES/IT Login

Encapsulation

1 min read | C++ Tutorial
๐ŸŽ“

Doing SIWES / IT attachment?

Get a structured training programme, a supervised digital logbook, and a completion certificate with LabsICT SIWES / IT.

Explore SIWES / IT Training

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;
}

๐Ÿงช Quick Quiz

What access modifier makes members accessible only within the class?