Polymorphism และ Function Table
เลือก behavior ผ่าน interface ร่วม
Polymorphism และ Function Table คืออะไร?
Dynamic polymorphism ให้ client เรียก operation ร่วมที่ concrete type เป็นผู้ทำ
ประเด็นสำคัญ
- เข้าใจกลไก C ก่อน abstraction ของ C++
- ใช้ RAII และ value semantics แสดง ownership
- เลือก abstraction ที่ type-safe แทน macro และ cast
ตัวอย่างโค้ด C และ C++
main.c
#include <stdio.h>
typedef struct Shape Shape;
struct Shape {
double value;
double (*area)(const Shape *shape);
};
double square_area(const Shape *shape) {
return shape->value * shape->value;
}
int main(void) {
Shape square = {4.0, square_area};
printf("area=%.1f\n", square.area(&square));
}
area=16.0
C++
main.cpp
#include <iostream>
struct Shape {
virtual double area() const = 0;
virtual ~Shape() = default;
};
struct Square : Shape {
double side;
explicit Square(double value) : side(value) {}
double area() const override { return side * side; }
};
int main() {
Square square(4);
const Shape& shape = square;
std::cout << "area=" << shape.area() << '\n';
}
area=16
เปรียบเทียบ C และ C++
C สร้าง object pointer และ function table เอง ส่วน virtual C++ ให้ dispatch คล้ายกันและ virtual destructor ที่ปลอดภัย
C
C ใช้ prefix, callback, macro และ context struct
C++
ภาษาให้ abstraction ที่มี scope และ type-safe
แบบฝึกหัด
รันทั้งสองเวอร์ชันแล้วแก้ไขเพื่อสังเกตความแตกต่างของภาษา
- เขียนกลไก C ก่อน
- แทน manual cleanup ด้วย RAII
- ตรวจ allocation และ virtual dispatch
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
โจทย์ทั้งหมด