Skip to content

Instantly share code, notes, and snippets.

@nilput
Created July 12, 2019 09:37
Show Gist options
  • Select an option

  • Save nilput/b90e26f2e25ce1a537aebe3b850c4d9c to your computer and use it in GitHub Desktop.

Select an option

Save nilput/b90e26f2e25ce1a537aebe3b850c4d9c to your computer and use it in GitHub Desktop.
Simple example about objects and polymorphism in C
#include <stdio.h>
struct base {
const struct vt *vt;
};
struct vt {
void (*who)(struct base *b);
void (*talk)(struct base *b);
};
struct cat {
struct base base;
const char *color;
};
struct dog {
struct base base;
int age;
};
void cat_who(struct base *cat_base) {
struct cat *cat = (struct cat *) cat_base;
printf("[%s Cat]\n", cat->color);
}
void cat_talk(struct base *cat_base) {
printf("%p says Meow\n", (void *) cat_base);
}
const struct vt cat_vt = {
.who = cat_who,
.talk = cat_talk,
};
void cat_init(struct cat *cat, const char *color) {
cat->base = (struct base){ .vt = &cat_vt };
cat->color = color;
}
void dog_who(struct base *dog_base) {
struct dog *dog = (struct dog *) dog_base;
printf("[%dyo Dog]\n", dog->age);
}
void dog_talk(struct base *dog_base) {
printf("%p Says Woof\n", (void *) dog_base);
}
const struct vt dog_vt = {
.who = dog_who,
.talk = dog_talk,
};
void dog_init(struct dog *dog, int age) {
dog->base = (struct base){ .vt = &dog_vt };
dog->age = age;
}
int main(void) {
struct cat cats[3];
cat_init(cats+0, "Yellow");
cat_init(cats+1, "Black");
cat_init(cats+2, "Grey");
struct dog dogs[2];
dog_init(dogs+0, 1);
dog_init(dogs+1, 2);
struct base *objects[] = {
(struct base *) (cats + 0),
(struct base *) (dogs + 0),
(struct base *) (cats + 1),
(struct base *) (cats + 2),
(struct base *) (dogs + 1),
};
int nobjects = sizeof objects / sizeof objects[0];
printf("Calling objects.who()\n");
for (int i=0; i<nobjects; i++) {
struct base *obj = objects[i];
obj->vt->who(obj);
}
printf("Calling objects.talk()\n");
for (int i=0; i<nobjects; i++) {
struct base *obj = objects[i];
obj->vt->talk(obj);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment