C++ moderno e alternative C

Polimorfismo e function table

Il polimorfismo dinamico consente una chiamata comune implementata dal tipo concreto.

Che cos’è Polimorfismo e function table?

Il polimorfismo dinamico consente una chiamata comune implementata dal tipo concreto.

Scegli comportamento tramite un’interfaccia comune.

Punti importanti

  • Comprendi prima il meccanismo C.
  • Usa RAII e value semantics per ownership.
  • Preferisci astrazioni type-safe a macro e cast.

Esempi di codice C e C++

C
Esegui →
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 previsto
area=16.0
C++
Esegui →
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 previsto
area=16

Confronto tra C e C++

C costruisce object pointer e tabella di funzioni; i virtual C++ generano dispatch simile con distruttore virtuale sicuro.

C

C usa prefissi, callback, macro e context espliciti.

C++

Il linguaggio offre astrazioni con scope, type-safe e spesso zero-overhead.

Esercizi pratici

Esegui entrambe le versioni e modificale per osservare le diverse garanzie.

  • Scrivi prima il meccanismo C.
  • Sostituisci cleanup manuale con RAII.
  • Misura allocation e virtual dispatch.