๐ Date: Feb 18, 2026
๐ง Mood: Shapeshifter ๐ฆ
๐ฅ Topic: OOPs Part 6: Polymorphism & Abstraction
๐ฆ 1. Polymorphism (Bahuroopiya)
The word comes from Greek: Poly (Many) + Morph (Forms).
Real Life Example: YOU.
- In College, you act like a Student.
- At Home, you act like a Son.
- In Game, you act like a Player.
Same Person (Object) -> Different Behaviors.
⚡ A. Compile Time Polymorphism
Also called Static Binding. The compiler knows before running the code which function to call.
1. Function Overloading
Using the Same Function Name but different parameters.
class Maths {
public:
// Form 1: 2 Integers
void add(int a, int b) {
cout << "Sum is: " << a + b << endl;
}
// Form 2: 3 Integers (Same Name!)
void add(int a, int b, int c) {
cout << "Sum is: " << a + b + c << endl;
}
};
int main() {
Maths m;
m.add(10, 20); // Compiler calls Form 1
m.add(10, 20, 30); // Compiler calls Form 2
return 0;
}
๐ B. Run Time Polymorphism
Also called Dynamic Binding. This happens while the code is running. This is achieved using Method Overriding.
The Magical `virtual` Keyword
If a Parent and Child have the same function, the Child's function "Overrides" the Parent's function.
class Animal {
public:
// "virtual" means: "Let the child decide at runtime"
virtual void speak() {
cout << "Animal Speaking..." << endl;
}
};
class Dog : public Animal {
public:
void speak() {
cout << "Woof Woof!" << endl;
}
};
int main() {
Animal *p; // Parent Pointer
Dog d; // Child Object
p = &d; // Pointer holding address of Child
p->speak();
// If "virtual" was NOT there -> Output: Animal Speaking...
// Because "virtual" IS there -> Output: Woof Woof!
return 0;
}
๐ญ 2. Abstraction (Hiding Complexity)
Real Life Example: When you press the Car Accelerator, the car moves. Do you know exactly how the engine valves open and fuel injects? NO. That complexity is "Abstracted" (Hidden) from you.
๐ ️ Abstract Class
A class that exists only to be inherited. You cannot create an object of it. It contains at least one Pure Virtual Function.
// Abstract Class (Blueprint Only)
class Shape {
public:
// Pure Virtual Function (Enforcing a Rule)
virtual void draw() = 0;
};
class Circle : public Shape {
public:
void draw() {
cout << "Drawing Circle ◯" << endl;
}
};
int main() {
// Shape s; // ❌ ERROR! Cannot create object of Abstract Class
Circle c;
c.draw(); // ✅ Works
return 0;
}
๐ Day 49 Challenge
- Create an abstract class
Paymentwith a pure virtual functionpay(). - Create two child classes:
GPayandCreditCard. - Implement
pay()differently in both (e.g., "Paying via UPI" vs "Paying via Card"). - In
main(), use a parent pointer to call both.
Next Up: Day 50 - The Grand Finale (Bank Management System Project).
No comments:
Post a Comment