SiamCafe.net Blog
Technology

OOP คือ C

oop คอ c
OOP คือ C | SiamCafe Blog
2025-07-19· อ. บอม — SiamCafe.net· 9,284 คำ

OOP ในภาษา C

OOP คือ C Object-Oriented Programming Encapsulation Inheritance Polymorphism Abstraction struct function pointer opaque vtable

OOP ConceptC ImplementationC++ Equivalent
Classstruct + functionsclass
Encapsulationopaque pointer + getter/setterprivate/public
Inheritancestruct embedding + castclass : public Base
Polymorphismfunction pointer in structvirtual function
Constructorcreate() function + mallocconstructor
Destructordestroy() function + freedestructor

Encapsulation

/* === Encapsulation in C === */

/* person.h - Public Interface */
/* typedef struct Person Person;  // Opaque - ไม่เห็น member */
/* Person* person_create(const char* name, int age); */
/* void person_destroy(Person* p); */
/* const char* person_get_name(const Person* p); */
/* int person_get_age(const Person* p); */
/* void person_set_age(Person* p, int age); */

/* person.c - Private Implementation */
/* #include "person.h" */
/* #include <stdlib.h> */
/* #include <string.h> */
/*  */
/* struct Person {           // Private - เห็นเฉพาะใน .c */
/*     char name[100]; */
/*     int age; */
/* }; */
/*  */
/* Person* person_create(const char* name, int age) { */
/*     Person* p = malloc(sizeof(Person)); */
/*     strncpy(p->name, name, 99); */
/*     p->age = age; */
/*     return p; */
/* } */
/*  */
/* void person_destroy(Person* p) { free(p); } */
/* const char* person_get_name(const Person* p) { return p->name; } */
/* int person_get_age(const Person* p) { return p->age; } */
/* void person_set_age(Person* p, int age) { */
/*     if (age > 0 && age < 200) p->age = age;  // Validation */
/* } */

/* Usage: */
/* Person* p = person_create("สมชาย", 25); */
/* printf("Name: %s Age: %d\n", person_get_name(p), person_get_age(p)); */
/* person_set_age(p, 26); */
/* person_destroy(p); */

from dataclasses import dataclass

@dataclass
class OOPPattern:
    concept: str
    c_technique: str
    header_file: str
    source_file: str

patterns = [
    OOPPattern("Encapsulation",
        "Opaque Pointer (typedef struct X X;)",
        "ประกาศ type + function prototype เท่านั้น",
        "define struct member + implement function"),
    OOPPattern("Private Members",
        "struct member อยู่ใน .c file เท่านั้น",
        "ผู้ใช้ไม่เห็น member ใน .h",
        "เข้าถึง member ได้เฉพาะใน .c"),
    OOPPattern("Getter/Setter",
        "function รับ pointer + return/set value",
        "const char* get_name(const X* x);",
        "return x->name; x->age = age;"),
    OOPPattern("Constructor",
        "create() function + malloc + init",
        "X* x_create(params);",
        "malloc + set member + return pointer"),
    OOPPattern("Destructor",
        "destroy() function + free",
        "void x_destroy(X* x);",
        "free(x); // cleanup resources"),
]

print("=== Encapsulation Patterns ===")
for p in patterns:
    print(f"  [{p.concept}] {p.c_technique}")
    print(f"    .h: {p.header_file}")
    print(f"    .c: {p.source_file}")

Inheritance & Polymorphism

/* === Inheritance & Polymorphism in C === */

/* Base: Shape */
/* typedef struct Shape { */
/*     int x, y; */
/*     double (*area)(void* self);     // Virtual function */
/*     void (*draw)(void* self);       // Virtual function */
/*     void (*destroy)(void* self);    // Virtual destructor */
/* } Shape; */

/* Derived: Circle */
/* typedef struct { */
/*     Shape base;       // MUST be first member (for casting) */
/*     int radius; */
/* } Circle; */
/*  */
/* double circle_area(void* self) { */
/*     Circle* c = (Circle*)self; */
/*     return 3.14159 * c->radius * c->radius; */
/* } */
/*  */
/* Circle* circle_create(int x, int y, int r) { */
/*     Circle* c = malloc(sizeof(Circle)); */
/*     c->base.x = x; */
/*     c->base.y = y; */
/*     c->base.area = circle_area;       // Set virtual function */
/*     c->base.draw = circle_draw; */
/*     c->base.destroy = circle_destroy; */
/*     c->radius = r; */
/*     return c; */
/* } */

/* Derived: Rectangle */
/* typedef struct { */
/*     Shape base; */
/*     int width, height; */
/* } Rectangle; */
/*  */
/* double rect_area(void* self) { */
/*     Rectangle* r = (Rectangle*)self; */
/*     return r->width * r->height; */
/* } */

/* Polymorphism: */
/* Shape* shapes[3]; */
/* shapes[0] = (Shape*)circle_create(0, 0, 5); */
/* shapes[1] = (Shape*)rect_create(0, 0, 10, 20); */
/* shapes[2] = (Shape*)circle_create(5, 5, 3); */
/*  */
/* for (int i = 0; i < 3; i++) { */
/*     printf("Area: %.2f\n", shapes[i]->area(shapes[i])); */
/*     shapes[i]->destroy(shapes[i]);  // Virtual destructor */
/* } */

@dataclass
class InheritancePattern:
    pattern: str
    c_code: str
    cpp_equivalent: str
    note: str

inheritance = [
    InheritancePattern("Base Class",
        "typedef struct { int x; double (*method)(void*); } Base;",
        "class Base { virtual double method() = 0; };",
        "function pointer = virtual function"),
    InheritancePattern("Derived Class",
        "typedef struct { Base base; int extra; } Derived;",
        "class Derived : public Base { int extra; };",
        "base ต้องเป็น member ตัวแรก"),
    InheritancePattern("Upcasting",
        "Base* b = (Base*)&derived;",
        "Base* b = &derived; // Implicit",
        "C ต้อง cast explicit C++ implicit"),
    InheritancePattern("Virtual Call",
        "b->method(b); // Call through function pointer",
        "b->method(); // Virtual dispatch",
        "C ส่ง self เอง C++ ส่ง this อัตโนมัติ"),
    InheritancePattern("Virtual Destructor",
        "b->destroy(b); // function pointer",
        "virtual ~Base() {}; delete b;",
        "C ต้องเรียก destroy เอง C++ อัตโนมัติ"),
]

print("=== Inheritance Patterns ===")
for i in inheritance:
    print(f"  [{i.pattern}]")
    print(f"    C: {i.c_code}")
    print(f"    C++: {i.cpp_equivalent}")
    print(f"    Note: {i.note}")

Real-world Examples

# === Real-world OOP in C ===

@dataclass
class RealExample:
    project: str
    oop_usage: str
    technique: str
    example: str

examples = [
    RealExample("Linux Kernel VFS",
        "Virtual File System ใช้ OOP Pattern",
        "struct file_operations มี function pointer (read write open close)",
        "ext4 xfs btrfs implement file_operations ต่างกัน → Polymorphism"),
    RealExample("GTK+ / GObject",
        "GUI Framework เขียนด้วย C แบบ OOP เต็มรูปแบบ",
        "GObject System: Inheritance Encapsulation Polymorphism Signal",
        "GtkWidget → GtkContainer → GtkBox → GtkButton (Inheritance chain)"),
    RealExample("SQLite",
        "Database Engine ใช้ OOP Pattern สำหรับ VFS Backend",
        "sqlite3_vfs struct มี function pointer สำหรับ File I/O",
        "Custom VFS สำหรับ In-memory Encrypted Compressed Storage"),
    RealExample("CPython",
        "Python Interpreter เขียนด้วย C ใช้ OOP",
        "PyObject base struct ทุก Python Object สืบทอดจาก PyObject",
        "PyLongObject PyListObject PyDictObject ล้วนมี PyObject เป็น base"),
    RealExample("Embedded Device Driver",
        "Device Driver ใช้ OOP Pattern สำหรับ HAL",
        "struct device_ops { init read write close } แต่ละ device implement ต่างกัน",
        "UART SPI I2C Driver ใช้ struct เดียวกัน implement ต่างกัน"),
]

print("=== Real-world OOP in C ===")
for e in examples:
    print(f"\n  [{e.project}] {e.oop_usage}")
    print(f"    Technique: {e.technique}")
    print(f"    Example: {e.example}")

เคล็ดลับ

OOP คืออะไร

Object-Oriented Programming Encapsulation Inheritance Polymorphism Abstraction struct function pointer C จำลอง OOP Linux GObject

Encapsulation ทำอย่างไร

Opaque Pointer typedef struct Header .h Source .c Private Member Getter Setter Create Destroy malloc free Validation

Inheritance ทำอย่างไร

Struct Embedding Base First Member Cast Upcasting Function Pointer Virtual Method Vtable Polymorphism Shape Circle Rectangle

เทียบกับ C++ อย่างไร

C struct function pointer void* cast manual C++ class virtual template auto Type Safety Performance ABI Platform Compiler

สรุป

OOP คือ C Encapsulation Opaque Pointer Inheritance Struct Embedding Polymorphism Function Pointer Linux GObject CPython Embedded

📖 บทความที่เกี่ยวข้อง

abstract ใน oop คืออ่านบทความ → oop python คืออ่านบทความ → oop data abstraction คืออ่านบทความ → oop design pattern คืออ่านบทความ → oop encapsulation คืออ่านบทความ →

📚 ดูบทความทั้งหมด →