ภาพรวม
Polymorphism (หลายรูปแบบ) เป็นคุณสมบัติหลักของ OOP แบ่งเป็น 2 ประเภทหลัก:
- Compile-time Polymorphism (Static Binding): Function Overloading, Operator Overloading, Templates
- Runtime Polymorphism (Dynamic Binding): Function Overriding (Virtual Functions)
ตัวอย่าง: Function Overloading (Compile-time)
#include <iostream>
using namespace std;
class Example {
public:
// Overload 1: รับ int 1 ตัว
void func(int a) {
cout << "\nThe value of a: " << a;
}
// Overload 2: รับ int 2 ตัว
void func(int a, int b) {
cout << "\nThe value of a: " << a;
cout << "\nThe value of b: " << b;
}
// Overload 3: รับ char 1 ตัว
void func(char c) {
cout << "\nThe value of c: " << c;
}
};
int main() {
Example obj;
cout << "\nOne int value";
obj.func(5); // เรียก Overload 1
cout << "\nOne char value";
obj.func('A'); // เรียก Overload 3
cout << "\nTwo int values";
obj.func(7, 2); // เรียก Overload 2
return 0;
}
ผลลัพธ์
One int value
The value of a: 5
One char value
The value of c: A
Two int values
The value of a: 7
The value of b: 2
Function Overloading Rules
- ต้องแตกต่างใน Parameter List (จำนวน, ประเภท, ลำดับ)
- Return Type เพียงอย่างเดียว ไม่เพียงพอสำหรับ Overloading
- Const Qualifier นับเป็นส่วนหนึ่งของ Signature
- Resolution เกิดขึ้นที่ Compile Time (Static Binding)
ตัวอย่างเพิ่มเติม: Constructor Overloading
class Point {
int x, y;
public:
Point() : x(0), y(0) {} // Default
Point(int x) : x(x), y(0) {} // 1 Param
Point(int x, int y) : x(x), y(y) {} // 2 Params
Point(const Point& other) : x(other.x), y(other.y) {} // Copy
};
Runtime Polymorphism: Function Overriding
#include <iostream>
#include <memory>
using namespace std;
class Animal {
public:
virtual void sound() { cout << "Some sound\n"; }
virtual ~Animal() = default;
};
class Dog : public Animal {
public:
void sound() override { cout << "Woof!\n"; }
};
class Cat : public Animal {
public:
void sound() override { cout << "Meow!\n"; }
};
void makeSound(Animal& animal) {
animal.sound(); // Dynamic Dispatch
}
int main() {
Dog dog;
Cat cat;
makeSound(dog); // Woof!
makeSound(cat); // Meow!
// Polymorphic Container
vector> animals;
animals.push_back(make_unique());
animals.push_back(make_unique());
for (auto& a : animals) a->sound();
}
การเปรียบเทียบ
| คุณสมบัติ | Overloading (Static) | Overriding (Dynamic) |
|---|---|---|
| Binding Time | Compile Time | Runtime |
| Mechanism | Name Mangling | Virtual Table (vtable) |
| Performance | เร็วกว่า (Direct Call) | ช้าอย่างน้อย (Indirect) |
| Flexibility | Fixed at Compile | Extensible at Runtime |
| Use Case | Same Operation, Different Params | Same Interface, Different Behavior |
สรุป
- Overloading: ชื่อฟังก์ชันเดียวกัน พารามิเตอร์ต่างกัน → Compiler เลือก
- Overriding: Virtual Function ใน Base, Override ใน Derived → Runtime เลือก
- ทั้งคู่เป็น Polymorphism แต่วัตถประสงค์และกลไกต่างกัน