Modern C++ और C Alternatives

Polymorphism और Function-Table Dispatch

Dynamic polymorphism common operation को concrete type से implement कराता है।

Polymorphism और Function-Table Dispatch क्या है?

Dynamic polymorphism common operation को concrete type से implement कराता है।

Common interface से behavior चुनें।

महत्वपूर्ण बातें

  • पहले C mechanism समझें।
  • Ownership के लिए RAII और value semantics उपयोग करें।
  • Macros और casts से अधिक type-safe abstractions चुनें।

C और C++ code examples

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));
}
अपेक्षित output
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';
}
अपेक्षित output
area=16

C और C++ की तुलना

C object pointer और function table explicit बनाता है; C++ virtual समान dispatch और safe virtual destructor देता है।

C

C prefixes, callbacks, macros और context structs उपयोग करता है।

C++

Language scoped और type-safe abstractions देता है।

अभ्यास

दोनों versions चलाकर बदलें और language guarantees की तुलना करें।

  • पहले C mechanism लिखें।
  • Manual cleanup को RAII से बदलें।
  • Allocation और virtual dispatch जाँचें।