Объявление и инициализация

Интерфейсы

//в C нет интерфейсов: их играет таблица указателей на функции
typedef struct Shape Shape;

//интерфейс: что умеет каждая фигура
struct ShapeOps {
    const char *name;
    double (*area)(const Shape *self);
    void (*scale)(Shape *self, double factor);
};

//объект хранит только указатель на таблицу своего типа: таблица одна для всех
//объектов и никогда не меняется
struct Shape {
    const struct ShapeOps *ops;
};

//единственная реализация интерфейса
typedef struct {
    Shape base;
    double width, height;
} Rect;

double rectArea(const Shape *self) {
    const Rect *rect = (const Rect *)self;
    return rect->width * rect->height;
}

void rectScale(Shape *self, double factor) {
    Rect *rect = (Rect *)self;
    rect->width *= factor;
    rect->height *= factor;
}

const struct ShapeOps rectOps = {"rect", rectArea, rectScale};

Rect rect = {{&rectOps}, 2, 3};

//код ниже видит только Shape и её таблицу
Shape *shape = &rect.base;
double area1 = shape->ops->area(shape);
//area1 is 6
shape->ops->scale(shape, 2);
double area2 = shape->ops->area(shape);
//area2 is 24
const char *name = shape->ops->name;
//name is "rect"

//таблица может расти, а объект по-прежнему держит один указатель
bool onePointer = sizeof(Shape) == sizeof(void *);
//onePointer is true

printf("area1 is %g\n", area1);
printf("area2 is %g\n", area2);
printf("name is %s\n", name);
printf("onePointer is %s\n", onePointer ? "true" : "false");