Polymorphism ဆိုတာ same interface/method name ကို object type မတူတဲ့အခါ behavior မတူအောင် လုပ်နိုင်တဲ့ OOP concept ပါ။ C++ မှာ runtime polymorphism အတွက် base class method ကို virtual လုပ်ပြီး derived class မှာ override လုပ်ပါတယ်။
cpp
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() {
cout << "Drawing a shape" << endl;
}
};
class Circle : public Shape {
public:
void draw() override {
cout << "Drawing a circle" << endl;
}
};
class Square : public Shape {
public:
void draw() override {
cout << "Drawing a square" << endl;
}
};
int main() {
Shape* shape1 = new Circle();
Shape* shape2 = new Square();
shape1->draw();
shape2->draw();
delete shape1;
delete shape2;
return 0;
}Shape* pointer က Circle နဲ့ Square object တွေကို ရည်ညွှန်းထားပါတယ်။ draw() ကိုခေါ်တဲ့အခါ actual object type အလိုက် Circle/Square version ကို run လုပ်ပါတယ်။ ဒါက virtual ကြောင့်ဖြစ်ပါတယ်။
You should see
Drawing a circle Drawing a squareInfo
Polymorphism က game objects, UI components, payment providers, notification channels စတဲ့ type မတူပေမယ့် action တူတဲ့ structure တွေမှာ အလွန်အသုံးဝင်ပါတယ်။