C++ mein Polymorphism ek aisa feature hai jo ek naam ko multiple forms mein use karne deta hai. Iska matlab hai – "many forms".
Yeh concept Object Oriented Programming (OOP) ka ek core pillar hai, aur C++ mein yeh do tariko se achieve hota hai:
- Compile-time Polymorphism
- Runtime Polymorphism
1. Compile-time Polymorphism
Compile-time polymorphism ka matlab hota hai ki function ya operator ka decision compile time par ho jaata hai. Isme do important cheezein aati hain:
a. Function Overloading
Jab ek hi function ka naam hota hai, lekin different parameters ke sath use kiya jaata hai, toh use function overloading kehte hain.
#include <iostream>
using namespace std;
class Print {
public:
void show(int x) {
cout << "Integer: " << x << endl;
}
void show(double y) {
cout << "Double: " << y << endl;
}
};
int main() {
Print obj;
obj.show(5);
obj.show(3.14);
return 0;
}
b. Operator Overloading
C++ mein aap operators ko bhi overload kar sakte ho – matlab unka behavior change kar sakte ho specific class ke liye.
#include <iostream>
using namespace std;
class Complex {
int real, imag;
public:
Complex(int r = 0, int i = 0) {
real = r;
imag = i;
}
Complex operator + (Complex const& obj) {
return Complex(real + obj.real, imag + obj.imag);
}
void display() {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex a(2, 3), b(1, 4);
Complex c = a + b;
c.display();
return 0;
}
2. Runtime Polymorphism
Yeh polymorphism run time par decide hota hai, aur yeh mostly inheritance ke through achieve hota hai.
a. Function Overriding
Jab base class aur derived class dono mein same function hota hai, aur derived class apni definition provide karti hai, toh usse overriding kehte hain.
#include <iostream>
using namespace std;
class Animal {
public:
virtual void sound() {
cout << "Some sound" << endl;
}
};
class Dog : public Animal {
public:
void sound() override {
cout << "Bark" << endl;
}
};
int main() {
Animal* a;
Dog d;
a = &d;
a->sound(); // Output: Bark
return 0;
}
Why virtual
keyword?
Virtual keyword ensure karta hai ki run-time par decide ho ki kaunsi function call hogi (base ya derived). Isko late binding ya dynamic dispatch kehte hain.
3. VTables and Late Binding
What is VTable?
Jab aap kisi class mein virtual
function likhte ho, toh compiler ek Virtual Table (VTable) banata hai. Is table mein function ke addresses store hote hain. Jab object create hota hai, tab VTable ka pointer (vptr
) set hota hai.
Late Binding ka matlab:
Function call runtime par decide hoti hai, compile-time par nahi. Yeh allow karta hai aapko derived class ka function call karna, even if pointer base class ka hai.
Real Life Example
class Vehicle {
public:
virtual void drive() {
cout << "Driving vehicle..." << endl;
}
};
class Car : public Vehicle {
public:
void drive() override {
cout << "Driving car..." << endl;
}
};
void testDrive(Vehicle* v) {
v->drive();
}
int main() {
Car myCar;
testDrive(&myCar); // Output: Driving car...
return 0;
}
Comments