Day 45: Introduction to OOPs (Part 2)

๐Ÿ“… Date: Feb 14, 2026

๐Ÿง  Mood: Security Guard ๐Ÿ‘ฎ‍♂️

๐Ÿ”ฅ Topic: OOPs Part 2: Access Modifiers & Encapsulation

๐Ÿ›‘ The Problem with "Public"

Yesterday, we made everything public:. It was easy, but dangerous.

Imagine a Bank Account class. If the balance is public, anyone can do this:

Account myAcc;
myAcc.balance = -500000; // ❌ Hacked! Balance can't be negative.
myAcc.balance = 9999999; // ❌ Fraud! Anyone can change money.

This is why we need Access Modifiers. We need to hide sensitive data.


๐Ÿ” Access Modifiers: The Security Guards

C++ provides 3 levels of security:

1. Private ๐Ÿ”’ (Default)

Only code inside the class can access it. No one from main() can touch it. (Like a Bank Vault).

2. Public ๐Ÿ“ข

Accessible from everywhere. (Like the Bank Counter).

3. Protected ๐Ÿ›ก️

Used in Inheritance (We will cover this in Day 46). Similar to Private but shared with children classes.


๐Ÿ› ️ Getters & Setters (Encapsulation)

If data is private, how do we use it?
We create public functions to access them securely. This concept is called Encapsulation (wrapping data and methods together).

  • Setter: A function to SET values (with validation check).
  • Getter: A function to GET (read) values.

๐Ÿ’ป The Secure Bank Code

#include <iostream>
using namespace std;

class BankAccount {
    // Data is hidden (Private)
    private: 
        int balance; 

    public:
        // SETTER (Write Access with Security)
        void setBalance(int amount) {
            if(amount < 0) {
                cout << "❌ Error: Balance cannot be negative!" << endl;
            } else {
                balance = amount;
                cout << "✅ Balance Updated!" << endl;
            }
        }

        // GETTER (Read Access)
        int getBalance() {
            return balance;
        }
};

int main() {
    BankAccount myAcc;
    
    // myAcc.balance = 5000; // ❌ ERROR! Private property.

    // Correct way: Use Setter
    myAcc.setBalance(-500); // Output: Error: Balance cannot be negative!
    myAcc.setBalance(1000); // Output: Balance Updated!

    // Correct way: Use Getter
    cout << "My Balance is: " << myAcc.getBalance();
    
    return 0;
}

๐Ÿ’ก Key Takeaway: We didn't allow direct access. We forced the user to go through setBalance(), where we added an if condition to check for valid input. This is Data Hiding.


๐Ÿš€ Day 45 Challenge

Create a class Student.

  1. Make age a private variable.
  2. Create a setAge(int a) function.
  3. Inside Setter, check if age is less than 0 or greater than 100. If yes, print "Invalid Age".
  4. In main(), try to set age as 150 and see what happens.

Next Up: Day 46 - Constructors & Destructors (The Life Cycle).

No comments:

Post a Comment