๐ 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.
- Make
agea private variable. - Create a
setAge(int a)function. - Inside Setter, check if age is less than 0 or greater than 100. If yes, print "Invalid Age".
- 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