Here's my ten-minute attempt:
Code:
#include <stdio.h>
/* Declare the shape object. */
struct shape;
struct ShapeVtbl
{
void (*Draw)(struct shape*);
void (*Eat)(struct shape*);
};
struct shape
{
const struct ShapeVtbl* vtbl; /* Points to the functions for this object,
which may be a circle or square. */
};
/* Functions which implement a circle object. */
void CircleDraw(struct shape* circle)
{
printf("Drawing a circle.\n");
}
void CircleEat(struct shape* circle)
{
printf("Mmm, circles! Doh!\n");
}
CircleCreate(struct shape* circle)
{
static const struct ShapeVtbl CircleVtbl = { CircleDraw, CircleEat };
circle->vtbl = &CircleVtbl;
}
/* Functions which implement a square object. */
void SquareDraw(struct shape* square)
{
printf("Drawing a square.\n");
}
void SquareEat(struct shape* square)
{
printf("This is going to be painful tomorrow!\n");
}
SquareCreate(struct shape* square)
{
static const struct ShapeVtbl SquareVtbl = { SquareDraw, SquareEat };
square->vtbl = &SquareVtbl;
}
int main(void)
{
int i;
/* Declare objects. */
struct shape Shapes[2];
/* Create objects. */
CircleCreate(&Shapes[0]);
SquareCreate(&Shapes[1]);
for (i = 0; i < 2; i++)
{
Shapes[i].vtbl->Eat(&Shapes[i]);
Shapes[i].vtbl->Draw(&Shapes[i]);
}
getchar();
return 0;
}