Title Slide
Encapsulation in C++
Secure Data Hiding for Robust Code
Your Name | Date
What is Encapsulation?
Definition:
"Bundling data (variables) and methods (functions) into a single unit (class) while
restricting access."
Real-world analogy:
A pill capsule (hides internal ingredients).
Key Benefits
1. Data Protection: Prevent unauthorized modifications.
2. Code Maintainability: Isolate changes to specific classes.
3. Modularity: Reusable components.
Access Specifiers
- private: Accessible only within the class.
- public: Accessible everywhere.
- protected: Accessible in derived classes.
Basic Code Example
class BankAccount {private: double balance; public: void deposit(double amount)
{ if (amount > 0) balance += amount; } double getBalance() { return balance; }}
Getters and Setters
class Student {private: string name; public: void setName(string n) { if (!n.empty())
name = n; } string getName() { return name; }}
Data Validation Example
class Temperature {private: double celsius; public: void setCelsius(double c) { if (c
>= -273.15) celsius = c; }}
Private Helper Methods
class Calculator {private: double square(double x) { return x * x; } public: void
calculate() { double result = square(5); }}
Encapsulation vs. Abstraction
- Encapsulation: How to hide data (e.g., private).
- Abstraction: What to hide (high-level design).
Bad Practice Alert!
class Employee {public: int salary;} (Problem: Direct access → No validation.)
Fixing Bad Code
class Employee {private: int salary; public: void setSalary(int s) { if (s >= 0) salary =
s; }}
Real-World Example
- std::string class:
- Hides internal char array.
- Exposes methods like length() and substr().
Advanced Example – Stack
class Stack {private: int data[100]; int top = -1; public: void push(int x) { data[+
+top] = x; } int pop() { return data[top--]; }}
Common Mistakes
1. Exposing internal arrays/pointers.
2. Forgetting const in getters.
Best Practices
1. Use private by default.
2. Validate data in setters.
3. Document public methods.
Q&A Slide
Questions?
Summary
- Encapsulation = Data hiding + Method bundling.
- Critical for secure, modular C++ code.
References
1. Programiz: C++ Encapsulation Guide
2. GeeksforGeeks: OOP Concepts

oop ppt.pptxfwefwefweqwedrqwerwerweewrewe