모던 C++와 C 대안

다형성과 함수 table dispatch

Dynamic polymorphism은 공통 operation을 concrete type이 구현하게 합니다.

다형성과 함수 table dispatch이란?

Dynamic polymorphism은 공통 operation을 concrete type이 구현하게 합니다.

공통 interface로 behavior를 선택합니다.

중요한 점

  • 먼저 C 메커니즘을 이해하세요.
  • RAII와 value semantics로 ownership을 표현하세요.
  • Macro와 cast보다 type-safe 추상화를 사용하세요.

C와 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을 명시합니다. C++ virtual은 비슷한 dispatch와 안전한 virtual destructor를 제공합니다.

C

C는 prefix, callback, macro와 context 구조를 씁니다.

C++

언어 기능이 scope와 type safety를 갖춘 추상화를 제공합니다.

연습 문제

두 버전을 실행하고 수정하여 각 언어의 보장을 관찰하세요.

  • C 메커니즘을 먼저 작성하세요.
  • 수동 cleanup을 RAII로 바꾸세요.
  • Allocation과 virtual dispatch를 확인하세요.