TeachMate
My ProgressJoin Session

Encapsulation

0/2 completed · ~0h 4m

All Topics
OOPLearnEncapsulation
1 / 2

Encapsulation

beginner
2 min read

Encapsulation bundles data (attributes) and methods (functions) into a single unit (class) and restricts direct access to some components.

Why Encapsulate?

  • Protect internal state from invalid changes
  • Hide implementation details
  • Provide controlled access through public methods
  • Make code easier to maintain and refactor

Access Levels

  • private: Only accessible within the class
  • protected: Accessible in class and derived classes
  • public: Accessible from anywhere

Example

class BankAccount {
private:
    double balance;  // Hidden from outside
public:
    BankAccount(double initial) : balance(initial) {}
    void deposit(double amount) {
        if (amount > 0) balance += amount;
    }
    double getBalance() const { return balance; }  // const: does not modify state
};

You can't directly set balance = -1000 because it's private. The deposit() method validates the input.

Getters and Setters

Provide controlled access to private members with validation logic.

Mark every getter const so it can be called on a const object and to signal that it does not modify the object's state.

Key takeaway: Encapsulation protects internal state — use private members with public getters/setters to control access and validate inputs.

TeachMate - Interactive learning platform for bachelor students

HomeLearnJoin Session|2 Subjects