Thuta Learning
C++
AdvancedProgrammingအခြေခံ

Polymorphism

C++သင်ခန်းစာ 2335 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • Static type နဲ့ dynamic type ကို ခွဲပြီး virtual call က ဘယ် function ကို run မလဲ ခန့်မှန်းနိုင်ဖို့
  • override နဲ့ final ကို သုံးပြီး signature အမှားတွေကို compiler က ဖမ်းအောင် လုပ်နိုင်ဖို့
  • Polymorphic base class တိုင်းမှာ virtual destructor ဘာကြောင့် လိုလဲ ရှင်းပြနိုင်ဖို့
  • Pure virtual function နဲ့ abstract interface တစ်ခု ဒီဇိုင်းဆွဲပြီး object slicing ကို ရှောင်နိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

ရိုးရိုးလေး ရှင်းရရင်

TV remote ပေါ်က power ခလုတ်ကို စဉ်းစားကြည့်ပါ။ Sony TV ကို နှိပ်ရင် Sony TV ပွင့်ပြီး Samsung TV ကို နှိပ်ရင် Samsung TV ပွင့်ပါတယ်။ ခလုတ် (interface) က တစ်ခုတည်းဖြစ်ပေမယ့် ဘာဖြစ်မလဲဆိုတာ ခလုတ်ကို နှိပ်လိုက်တဲ့ စက် (object) ပေါ်မှာ မူတည်ပါတယ်။

Polymorphism ဆိုတာ "ပုံစံ အများအပြား" လို့ အဓိပ္ပာယ်ရပါတယ်။ C++ မှာ base class ရဲ့ function ကို virtual လို့ မှတ်ထားရင် Shape& ဒါမှမဟုတ် Shape* ကနေ draw() ကို ခေါ်တဲ့အခါ program က run နေချိန်မှာ object ရဲ့ တကယ့် type ကို ကြည့်ပြီး Circle ရဲ့ draw() လား Square ရဲ့ draw() လား ရွေးပေးပါတယ်။ Caller က shape အမျိုးအစား ဘယ်နှမျိုး ရှိလဲ သိစရာ မလိုပါဘူး။

Problem → Why → Solution

ပြဿနာ: virtual မပါရင် base version ပဲ run တယ်

Circle က Shape ရဲ့ draw() ကို ကိုယ်ပိုင် version နဲ့ အစားထိုးထားပါတယ်။ ဒါပေမယ့် render() က Shape& ကို လက်ခံလို့ Circle ကို ပို့လိုက်တဲ့အခါ "Drawing a circle" အစား "Drawing a shape" ထွက်ပါတယ်။ Error လည်း မရှိ၊ warning လည်း မရှိပါဘူး — program က မှားတဲ့ function ကို တိတ်တိတ်လေး ခေါ်နေတာပါ။

no_virtual.cpp
#include <iostream>

class Shape {
public:
    void draw() const { std::cout << "Drawing a shape\n"; }   // not virtual
};

class Circle : public Shape {
public:
    void draw() const { std::cout << "Drawing a circle\n"; }
};

void render(const Shape& s) {
    s.draw();          // decided at compile time: always Shape::draw
}

int main() {
    Circle c;
    render(c);         // prints "Drawing a shape"
}

ဘာကြောင့် Shape::draw ကို ရွေးတာလဲ

virtual မပါတဲ့ function call ကို compiler က compile time မှာ ဆုံးဖြတ်ပြီး အဲဒီအချိန်မှာ သိတာက s ရဲ့ static type ဖြစ်တဲ့ const Shape& ပဲ ရှိပါတယ်။ render() ကို နောက်ပိုင်း ဘယ် object နဲ့ ခေါ်မလဲဆိုတာ compiler မသိပါဘူး။ draw() ကို virtual လုပ်လိုက်ရင် ဆုံးဖြတ်ချက်ကို runtime ထိ ရွှေ့ပြီး object ရဲ့ တကယ့် type (dynamic type) အလိုက် ရွေးပါတယ်။

Core concept: virtual call က dynamic type ကို လိုက်တယ်

Expression တိုင်းမှာ type နှစ်မျိုး ရှိပါတယ်။ Static type က code ထဲမှာ ရေးထားတဲ့ type (const Shape& s) ဖြစ်ပြီး dynamic type ကတော့ run နေချိန်မှာ s ညွှန်နေတဲ့ object ရဲ့ တကယ့် type (Circle) ပါ။ Non-virtual function ကို static type နဲ့ ရွေးပြီး virtual function ကို dynamic type နဲ့ ရွေးပါတယ်။ ဒီ dynamic dispatch က reference ဒါမှမဟုတ် pointer ကနေ ခေါ်မှပဲ အလုပ်လုပ်ပါတယ် — Shape s = circle; လို value တစ်ခုမှာ dynamic type က Shape ပဲ ဖြစ်နိုင်လို့ပါ။

Derived class မှာ virtual function ကို အစားထိုးတဲ့အခါ override keyword ကို အမြဲ ရေးပါ။ Override လုပ်ဖို့ name၊ parameter တွေနဲ့ const က base နဲ့ အတိအကျ ကိုက်ရပါတယ်။ const တစ်ခု ကျန်ခဲ့ရင် override မဟုတ်ဘဲ function အသစ်တစ်ခု ဖြစ်သွားပြီး base version ပဲ ဆက် run နေပါမယ် — override ပါရင်တော့ compiler က ဒီအမှားကို error နဲ့ ဖမ်းပေးပါတယ်။ final ကတော့ "ဒီ function ကို ဒါမှမဟုတ် ဒီ class ကို နောက်ထပ် override/derive မလုပ်ရ" လို့ ပိတ်တာပါ။

Polymorphic object တွေကို base pointer ကနေ ဖျက်တဲ့အခါ base class ရဲ့ destructor က virtual ဖြစ်ရပါမယ်။ Shape* p = new Circle; delete p; မှာ ~Shape() က virtual မဟုတ်ရင် behavior က undefined ဖြစ်ပြီး Circle ရဲ့ destructor မ run တာမျိုး ဖြစ်နိုင်ပါတယ်။ g++ -Wall က ဒီအခြေအနေကို "deleting object of polymorphic class type 'Shape' which has non-virtual destructor might cause undefined behavior" လို့ သတိပေးပါတယ်။ စည်းမျဉ်းက ရိုးရှင်းပါတယ် — virtual function ပါတဲ့ base class တိုင်းမှာ virtual ~Base() = default; ကို ထည့်ပါ။

text
How compilers typically implement virtual calls (vtables)
---------------------------------------------------------
shapes[0] -> Circle object         Circle's vtable
             +----------------+    +------------------------+
             | vptr ----------+--> | Circle::~Circle()      |
             | Shape part     |    | Circle::draw() const   |
             +----------------+    +------------------------+
shapes[1] -> Square object         Square's vtable
             +----------------+    +------------------------+
             | vptr ----------+--> | Square::~Square()      |
             | Shape part     |    | Square::draw() const   |
             +----------------+    +------------------------+
shape->draw(): read vptr, load the draw entry, call it.

Standard က implementation ကို သတ်မှတ်မထားပေမယ့် compiler အများစုက class တစ်ခုစီအတွက် virtual function pointer table (vtable) တစ်ခုစီ ထားပြီး polymorphic object တိုင်းထဲမှာ အဲဒီ table ကို ညွှန်တဲ့ hidden pointer (vptr) တစ်ခု ထည့်ပါတယ်။ ဒါကြောင့် virtual call တစ်ခုက pointer တစ်ဆင့် ဖြတ်ပြီး ခေါ်ရတဲ့ indirect call ဖြစ်ကာ object တစ်ခုစီမှာ pointer တစ်ခုစာ နေရာ ပိုယူပါတယ်။

မှတ်ထားရမယ့် ပုံစံ: reference ကနေ တကယ့် object ဆီ
  1. Base& ဒါမှမဟုတ် Base* ကနေ ခေါ်
  2. virtual ဖြစ်လား စစ်
  3. Object ရဲ့ dynamic type ကို ကြည့်
  4. အဲဒီ class ရဲ့ override ကို run

Function က virtual မဟုတ်ရင် ဒါမှမဟုတ် object ကို value နဲ့ ကိုင်ထားရင် static type ရဲ့ version ကိုပဲ run ပါတယ်။

အထွေထွေ ပုံစံ

cpp
class Base {
public:
    virtual ~Base() = default;                  // safe delete through Base*
    virtual Result action() const = 0;          // pure virtual: must override
    virtual Result hook() const { return fallback; }  // may override
};
class Derived final : public Base {             // final: no further deriving
public:
    Result action() const override;             // checked by the compiler
};

void use(const Base& obj) { obj.action(); }     // runs Derived::action

Base မှာ virtual destructor ကို အရင် ထည့်ပါ။ = 0 ပါတဲ့ pure virtual function က derived class တိုင်း မဖြစ်မနေ override လုပ်ရမယ့် function ဖြစ်ပြီး ရိုးရိုး virtual function ကတော့ default behavior ပေးထားလို့ override လုပ်ချင်မှ လုပ်ပါတယ်။ Derived ဘက်မှာ override ကို အမြဲ ရေးပြီး object ကို base reference ဒါမှမဟုတ် pointer နဲ့ ကိုင်ပါ။

Example: shape အမျိုးမျိုးကို loop တစ်ခုတည်းနဲ့ ဆွဲခြင်း

ဒီ example မှာ Circle နဲ့ Square ကို std::unique_ptr<Shape> အဖြစ် vector တစ်ခုထဲ သိမ်းပြီး loop တစ်ခုတည်းနဲ့ draw() ကို ခေါ်ပါတယ်။ Loop က Shape အကြောင်းပဲ သိပေမယ့် object တစ်ခုစီရဲ့ ကိုယ်ပိုင် version ကို run ပါတယ်။ Base မှာ virtual destructor ပါလို့ unique_ptr တွေက object တွေကို မှန်မှန်ကန်ကန် ဖျက်ပေးပါတယ်။

polymorphism.cpp
#include <iostream>
#include <memory>
#include <vector>
using namespace std;

class Shape {
  public:
    virtual ~Shape() = default;

    virtual void draw() const {
        cout << "Drawing a shape" << endl;
    }
};

class Circle : public Shape {
  public:
    void draw() const override {
        cout << "Drawing a circle" << endl;
    }
};

class Square : public Shape {
  public:
    void draw() const override {
        cout << "Drawing a square" << endl;
    }
};

int main() {
    vector<unique_ptr<Shape>> shapes;
    shapes.push_back(make_unique<Circle>());
    shapes.push_back(make_unique<Square>());

    for (const auto& shape : shapes) {
        shape->draw();
    }
    return 0;
}

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. Line 8virtual ~Shape() = default;

    unique_ptr<Shape> က object ကို Shape* ကနေ delete လုပ်မှာမို့ ဒီ virtual destructor က Circle နဲ့ Square ရဲ့ destructor တွေ run အောင် လုပ်ပေးပါတယ်။

  2. Line 10virtual void draw() const {

    virtual ကြောင့် draw() ကို dynamic type နဲ့ ရွေးပါတယ်။ Body ပါလို့ override မလုပ်တဲ့ derived class တွေအတွက် default behavior ဖြစ်ပါတယ်။

  3. Line 17void draw() const override {

    Shape::draw() const ကို အစားထိုးပါတယ်။ const ကို ချန်ခဲ့ရင် override ကြောင့် compile error ရပြီး bug ကို ချက်ချင်း သိရပါတယ်။

  4. Line 30vector<unique_ptr<Shape>> shapes;

    Container ထဲမှာ object တွေကို တိုက်ရိုက် မသိမ်းဘဲ pointer နဲ့ သိမ်းပါတယ်။ vector<Shape> ဆိုရင် Circle ရဲ့ Shape အပိုင်းကိုပဲ copy ကူးပြီး slicing ဖြစ်ပါမယ်။

  5. Line 35shape->draw();

    shape ရဲ့ static type က unique_ptr<Shape> ပေမယ့် ပထမ round မှာ Circle::draw()၊ ဒုတိယ round မှာ Square::draw() ကို run ပြီး "Drawing a circle" နဲ့ "Drawing a square" ထွက်ပါတယ်။

You should see
Drawing a circle
Drawing a square

Pure virtual function နဲ့ abstract class

Base class က အဓိပ္ပာယ်ရှိတဲ့ default behavior မပေးနိုင်တဲ့အခါ function ကို = 0 နဲ့ pure virtual လုပ်ပါတယ်။ Pure virtual function တစ်ခုခု ပါတဲ့ class က abstract class ဖြစ်ပြီး အဲဒီ type နဲ့ object ကို တိုက်ရိုက် create လုပ်လို့ မရပါဘူး — Notifier n; က "cannot declare variable 'n' to be of abstract type 'Notifier'" error ပေးပါတယ်။ Abstract class က "ဒီ interface ကို ပံ့ပိုးတဲ့ class တိုင်း ဒီ function တွေ ရှိရမယ်" ဆိုတဲ့ ကတိပါ။

notifier.cpp
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <vector>

class Notifier {
public:
    virtual ~Notifier() = default;
    virtual void send(const std::string& message) const = 0;   // pure virtual
};

class EmailNotifier : public Notifier {
public:
    explicit EmailNotifier(std::string address) : address_(std::move(address)) {}
    void send(const std::string& message) const override {
        std::cout << "email to " << address_ << ": " << message << '\n';
    }
private:
    std::string address_;
};

class SmsNotifier final : public Notifier {
public:
    explicit SmsNotifier(std::string phone) : phone_(std::move(phone)) {}
    void send(const std::string& message) const override {
        std::cout << "sms to " << phone_ << ": " << message << '\n';
    }
private:
    std::string phone_;
};

int main() {
    std::vector<std::unique_ptr<Notifier>> channels;
    channels.push_back(std::make_unique<EmailNotifier>("aye@example.com"));
    channels.push_back(std::make_unique<SmsNotifier>("09-123456"));
    for (const auto& channel : channels) channel->send("Your order has shipped");
}

Output က "email to aye@example.com: Your order has shipped" နဲ့ "sms to 09-123456: Your order has shipped" ပါ။ Channel အသစ် (ဥပမာ push notification) ထပ်ထည့်ချင်ရင် Notifier ကနေ ဆင်းသက်တဲ့ class တစ်ခု ရေးပြီး vector ထဲ ထည့်ရုံပါပဲ၊ loop ကို ပြင်စရာ မလိုပါဘူး။ SmsNotifier က final ဖြစ်လို့ အဲဒီကနေ ထပ် derive လုပ်ရင် compile error ပါ။

Object slicing

Derived object ကို base type ရဲ့ value အဖြစ် copy ကူးလိုက်ရင် base အပိုင်းကိုပဲ copy ကူးပြီး derived အပိုင်းကို ဖြတ်ပစ်ပါတယ် — ဒါကို slicing လို့ ခေါ်ပါတယ်။ Copy ရဲ့ dynamic type က base ဖြစ်သွားလို့ virtual function တွေကလည်း base version ကို run ပါတော့တယ်။ Polymorphic object တွေကို reference၊ pointer ဒါမှမဟုတ် smart pointer နဲ့ပဲ ပို့ပြီး သိမ်းပါ။

slicing.cpp
#include <iostream>

class Shape {
public:
    virtual ~Shape() = default;
    virtual void draw() const { std::cout << "Drawing a shape\n"; }
};

class Circle : public Shape {
public:
    void draw() const override { std::cout << "Drawing a circle\n"; }
};

void byValue(Shape s) { s.draw(); }              // copies only the Shape part
void byReference(const Shape& s) { s.draw(); }   // sees the whole Circle

int main() {
    Circle c;
    byValue(c);
    byReference(c);
}

byValue(c) က "Drawing a shape" ကို ထုတ်ပြီး byReference(c) က "Drawing a circle" ကို ထုတ်ပါတယ်။ Function signature မှာ & တစ်လုံး ကွာတာနဲ့ behavior လုံးဝ ပြောင်းသွားပါတယ်။

dynamic_cast — derived type ကို တကယ် လိုအပ်တဲ့အခါ

တစ်ခါတစ်ရံ base pointer တစ်ခုက တကယ်တော့ Circle ဟုတ်မဟုတ် စစ်ပြီး Circle မှာပဲ ရှိတဲ့ member ကို သုံးချင်ပါတယ်။ dynamic_cast<const Circle*>(p) က runtime မှာ စစ်ပြီး Circle ဖြစ်ရင် pointer ကို၊ မဟုတ်ရင် nullptr ကို ပြန်ပေးပါတယ်။ Reference ကို cast လုပ်ရင်တော့ မအောင်မြင်တဲ့အခါ std::bad_cast exception ကို throw လုပ်ပါတယ်။ dynamic_cast က virtual function အနည်းဆုံး တစ်ခု ပါတဲ့ polymorphic type တွေမှာပဲ အလုပ်လုပ်ပါတယ်။

dynamic_cast.cpp
#include <iostream>
#include <memory>
#include <vector>

class Shape {
public:
    virtual ~Shape() = default;
    virtual double area() const = 0;
};

class Circle : public Shape {
public:
    explicit Circle(double r) : radius(r) {}
    double area() const override { return 3.14159 * radius * radius; }
    double radius;
};

class Square : public Shape {
public:
    explicit Square(double s) : side(s) {}
    double area() const override { return side * side; }
    double side;
};

int main() {
    std::vector<std::unique_ptr<Shape>> shapes;
    shapes.push_back(std::make_unique<Circle>(1.0));
    shapes.push_back(std::make_unique<Square>(2.0));
    for (const auto& s : shapes) {
        if (const auto* c = dynamic_cast<const Circle*>(s.get())) {
            std::cout << "circle with radius " << c->radius << '\n';
        } else {
            std::cout << "not a circle, area " << s->area() << '\n';
        }
    }
}

Output က "circle with radius 1" နဲ့ "not a circle, area 4" ပါ။ dynamic_cast တွေ if-else chain ရှည်ရှည် ဖြစ်လာရင်တော့ ဒီဇိုင်း ပြန်ကြည့်ဖို့ လက္ခဏာပါ — type တစ်ခုစီကို စစ်နေမယ့်အစား အဲဒီ behavior ကို virtual function အဖြစ် base ထဲ ထည့်တာ များသောအားဖြင့် ပိုကောင်းပါတယ်။

လက်တွေ့ project တွေမှာ

Real project တွေမှာ ဘယ်လို သုံးလဲ

Type မတူပေမယ့် action တူတဲ့ နေရာတိုင်းမှာ polymorphism ကို တွေ့ရပါတယ် — game ထဲက entity တိုင်းရဲ့ update()၊ GUI widget တွေရဲ့ paint/draw function (Qt ရဲ့ QWidget::paintEvent က virtual ပါ)၊ payment provider တွေ၊ notification channel တွေ၊ application ထဲ ထည့်လို့ရတဲ့ plugin တွေပါ။ Abstract interface ကို ဆန့်ကျင်ပြီး code ရေးထားရင် test တွေမှာ email တကယ် မပို့တဲ့ FakeNotifier လို test double ကို ထည့်ပေးလို့ ရပါတယ်။

Virtual call တစ်ခုရဲ့ ကုန်ကျစရိတ်က များသောအားဖြင့် သေးငယ်ပါတယ် (indirect call တစ်ခု)၊ ဒါပေမယ့် compiler က inline လုပ်ဖို့ ခက်လာလို့ တစ်စက္ကန့်ကို သန်းချီ ခေါ်တဲ့ အလွန်တင်းကျပ်တဲ့ loop တွေမှာ သိသာနိုင်ပါတယ်။ ဒီလို အခြေအနေမှာ template တွေနဲ့ compile-time polymorphism (lesson 27) ဒါမှမဟုတ် std::variant နဲ့ std::visit ကို အစားထိုး သုံးကြပါတယ်။ ပုံမှန် application code မှာတော့ ရှင်းလင်းမှုအတွက် virtual function က ကောင်းတဲ့ default ပါ။

အမှားများ

အဖြစ်များတဲ့ အမှားတွေ

1. Base မှာ virtual destructor မေ့တာ

Shape* p = new Circle; delete p; မှာ ~Shape() က virtual မဟုတ်ရင် undefined behavior ပါ — Circle ရဲ့ destructor မ run လို့ Circle ပိုင်တဲ့ resource တွေ ယိုစိမ့်နိုင်ပါတယ်။ Base class ထဲ virtual function တစ်ခု ထည့်တိုင်း virtual ~Shape() = default; ကိုလည်း တစ်ခါတည်း ထည့်ပါ။

2. override မရေးဘဲ signature လွဲတာ

Base မှာ virtual void draw() const ဖြစ်ပြီး derived မှာ void draw() လို့ (const မပါဘဲ) ရေးရင် function အသစ် ဖြစ်သွားပြီး Shape& ကနေ ခေါ်တိုင်း base version ပဲ run ပါတယ်။ void draw() override လို့ ရေးထားရင်တော့ g++ က "'void Circle::draw()' marked 'override', but does not override" error နဲ့ ချက်ချင်း ဖမ်းပေးပါတယ်။

3. Polymorphic object ကို value နဲ့ သိမ်းတာ

std::vector<Shape> ထဲ Circle ကို push_back လုပ်ရင် ဒါမှမဟုတ် void render(Shape s) လို value parameter နဲ့ ပို့ရင် slicing ဖြစ်ပြီး derived behavior ပျောက်ပါတယ်။ std::vector<std::unique_ptr<Shape>> နဲ့ const Shape& ကို သုံးပါ။

4. Constructor ထဲကနေ virtual function ခေါ်တာ

Shape ရဲ့ constructor run နေတဲ့ အချိန်မှာ Circle အပိုင်း မဆောက်ရသေးလို့ object က Shape အဖြစ်ပဲ ပြုမူပါတယ်။ အဲဒီအချိန် draw() ကို ခေါ်ရင် Circle::draw() မဟုတ်ဘဲ Shape::draw() run ပါတယ် (pure virtual ဆိုရင် ပိုဆိုးပါတယ်)။ Destructor ထဲမှာလည်း ဒီအတိုင်းပါပဲ။ Construction ပြီးမှ ခေါ်ပါ။

Best Practices

အကောင်းဆုံး အလေ့အကျင့်များ

  • Polymorphic base class တိုင်းမှာ public virtual destructor ထည့်ပါ။
  • Override လုပ်တဲ့ function တိုင်းမှာ override ကို ရေးပြီး derived class မှာ virtual ကို ထပ်မရေးပါနဲ့ (override က လုံလောက်ပါတယ်)။
  • Interface တွေကို data မပါတဲ့ pure virtual function တွေနဲ့ ဒီဇိုင်းဆွဲပြီး ownership ကို std::unique_ptr နဲ့ ကိုင်ပါ။
  • dynamic_cast ကို ခြွင်းချက်အဖြစ်ပဲ သုံးပြီး type စစ်တဲ့ chain အစား virtual function ကို ဦးစားပေးပါ။

Mini challenge

Mini challenge: payment fee များ

Online shop တစ်ခုအတွက် abstract Payment interface နဲ့ payment နည်းလမ်း သုံးမျိုး ရေးပြီး loop တစ်ခုတည်းနဲ့ fee တွေကို တွက်ပါ။ ငွေပမာဏတွေကို integer cent နဲ့ ကိုင်ပါ။

  • Payment မှာ virtual destructor၊ pure virtual name() const နဲ့ fee(int amountCents) const ပါရမယ်
  • CardPayment = 3%၊ CashOnDelivery = အမြဲ 150၊ WalletPayment (final) = 1% ဒါပေမယ့် အနည်းဆုံး 50
  • Override လုပ်တဲ့ function တိုင်းမှာ override ပါရမယ်
  • std::vector<std::unique_ptr<Payment>> ကို loop ပတ်ပြီး amount 2000 အတွက် fee တစ်ခုစီနဲ့ စုစုပေါင်းကို print ထုတ်ရမယ်
payments.cpp
#include <algorithm>
#include <iostream>
#include <memory>
#include <string>
#include <vector>

class Payment {
public:
    // TODO: virtual destructor
    // TODO: pure virtual std::string name() const
    // TODO: pure virtual int fee(int amountCents) const
};

// TODO: class CardPayment       - 3% of the amount
// TODO: class CashOnDelivery    - a flat 150
// TODO: class WalletPayment     - final, 1% but never less than 50

int printFees(const std::vector<std::unique_ptr<Payment>>& methods, int amountCents) {
    // TODO: print "<name> fee: <fee>" for each method and return the sum
}

int main() {
    // TODO: fill the vector, call printFees(methods, 2000), print the total
}

ရလဒ်: Program က အောက်ပါအတိုင်း print ထုတ်ရပါမယ်: card fee: 60 cash on delivery fee: 150 wallet fee: 50 total fees: 260

အရိပ်အမြွက် ကြည့်ရန်

3% ကို amountCents * 3 / 100 နဲ့ integer arithmetic နဲ့ တွက်ပါ။ Minimum အတွက် std::max(amountCents / 100, 50) ကို သုံးပါ။ CashOnDelivery ရဲ့ fee() က amount ကို မသုံးလို့ parameter နာမည် မပေးဘဲ int fee(int) const override လို့ ရေးရင် unused-parameter warning မတက်ပါဘူး။

အဖြေ ကြည့်ရန်
payments.cpp
#include <algorithm>
#include <iostream>
#include <memory>
#include <string>
#include <vector>

class Payment {
public:
    virtual ~Payment() = default;
    virtual std::string name() const = 0;
    virtual int fee(int amountCents) const = 0;
};

class CardPayment : public Payment {
public:
    std::string name() const override { return "card"; }
    int fee(int amountCents) const override { return amountCents * 3 / 100; }
};

class CashOnDelivery : public Payment {
public:
    std::string name() const override { return "cash on delivery"; }
    int fee(int) const override { return 150; }
};

class WalletPayment final : public Payment {
public:
    std::string name() const override { return "wallet"; }
    int fee(int amountCents) const override { return std::max(amountCents / 100, 50); }
};

int printFees(const std::vector<std::unique_ptr<Payment>>& methods, int amountCents) {
    int total = 0;
    for (const auto& method : methods) {
        int fee = method->fee(amountCents);      // dispatches on the real type
        std::cout << method->name() << " fee: " << fee << '\n';
        total += fee;
    }
    return total;
}

int main() {
    std::vector<std::unique_ptr<Payment>> methods;
    methods.push_back(std::make_unique<CardPayment>());
    methods.push_back(std::make_unique<CashOnDelivery>());
    methods.push_back(std::make_unique<WalletPayment>());

    int total = printFees(methods, 2000);
    std::cout << "total fees: " << total << '\n';
}

Quick Quiz 1 / 3

Shape::draw() က virtual ဖြစ်ပြီး Circle က override လုပ်ထားတယ်။ void render(Shape s) { s.draw(); } ကို Circle c; render(c); လို့ ခေါ်ရင် ဘာ print ထုတ်မလဲ။

Quick Quiz 2 / 3

Base မှာ virtual void draw() const; ရှိပြီး Derived မှာ void draw() override; လို့ ရေးရင် ဘာဖြစ်မလဲ။

Quick Quiz 3 / 3

Shape မှာ virtual draw() ရှိပေမယ့် destructor က virtual မဟုတ်ပါဘူး။ Shape* p = new Square; delete p; အကြောင်း ဘယ်ဟာ မှန်လဲ။

မှတ်ထားရမယ့် အချက်များ

  • virtual function ကို reference ဒါမှမဟုတ် pointer ကနေ ခေါ်ရင် object ရဲ့ dynamic type အလိုက် override ကို run ပါတယ်။
  • Override လုပ်တိုင်း override ကို ရေးပါ၊ final က နောက်ထပ် override/derive လုပ်တာကို ပိတ်ပါတယ်။
  • Polymorphic base class တိုင်းမှာ virtual destructor လိုပြီး pure virtual (= 0) function ပါတဲ့ class က abstract ဖြစ်ပါတယ်။
  • Value နဲ့ copy ကူးရင် slicing ဖြစ်လို့ polymorphic object တွေကို reference/smart pointer နဲ့ ကိုင်ပြီး dynamic_cast ကို ရှားရှားပါးပါးပဲ သုံးပါ။

The Current ISO C++ Standard (C++23) — Standard C++ Foundation

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

Polymorphism | Thuta Learning