C++ Encapsulation

C++ Tutorial

🔐 C++ Encapsulation

Encapsulation is a key idea in Object-Oriented Programming (OOP).
It means putting data (variables) and methods (functions) together in a class and limiting direct access to the data.


🔹 1. Why Encapsulation?

  • Protects data from unauthorized access

  • Improves security

  • Makes code easier to maintain

  • Allows controlled access through methods


🔹 2. How Encapsulation Works in C++

Encapsulation is achieved using:

  • Classes

  • Access specifiers (private, public, protected)

  • Getter and Setter methods


🔹 3. Basic Encapsulation Example


 

Usage:

Account a;
a.setBalance(5000);
cout << a.getBalance();

✔ Direct access blocked
✔ Controlled access allowed


🔹 4. Encapsulation with Validation


 

✔ Prevents invalid data


🔹 5. Read-Only Encapsulation (const Getter)


 


🔹 6. Write-Only Encapsulation


 


🔹 7. Encapsulation vs Data Hiding

Encapsulation Data Hiding
Bundling data + methods Restricting access
Achieved using classes Achieved using private
Broader concept Part of encapsulation

🔹 8. Real-Life Example

ATM Machine

  • Data: PIN, Balance (hidden)

  • Methods: Withdraw(), CheckBalance()

User cannot directly change balance.


🔹 9. Benefits of Encapsulation

  • Better control over data

  • Reduced complexity

  • Improved security

  • Easier debugging and testing

  • Flexibility to change implementation


❌ Common Mistakes

class Test {
public:
int x; // ❌ breaks encapsulation
};

📌 Summary

  • Encapsulation = data + methods in a class

  • Protects data using access specifiers

  • Access data through getters/setters

  • Improves security and maintainability

  • Foundation of good OOP design

You may also like...