Thuta Learning
ရှာဖွေရန်
AdvancedProgrammingbeginner

Polymorphism

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

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 square

Info

Polymorphism က game objects, UI components, payment providers, notification channels စတဲ့ type မတူပေမယ့် action တူတဲ့ structure တွေမှာ အလွန်အသုံးဝင်ပါတယ်။

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • Base class method ကို virtual မလုပ်ထားရင် derived class version မဟုတ်ဘဲ base class version run ဖြစ်နိုင်ပါတယ်။ override သုံးတာက typo/error ကို compiler ကဖမ်းနိုင်စေပါတယ်။
Polymorphism | Thuta Learning