Skip to content

Instantly share code, notes, and snippets.

@xplorld
Created June 1, 2017 12:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xplorld/bf59018fbdf1d244c79e64d2df685323 to your computer and use it in GitHub Desktop.
Save xplorld/bf59018fbdf1d244c79e64d2df685323 to your computer and use it in GitHub Desktop.
a simple virtual-table implemented polymorphism simulation in C
#include <stdio.h>
#include <stdlib.h>
struct Base;
struct Derived;
int f_Base(struct Base * b);
int f_Derived(struct Derived* d);
typedef struct {
int (*f)(struct Base *);
} VTable_Base;
VTable_Base vtable_base;
VTable_Base vtable_derived;
int vptr_init() {
vtable_base.f = f_Base;
//warning: incompatible pointer types assigning to 'int (*)(struct Base *)' from 'int (struct Derived *)'
vtable_derived.f = f_Derived;
return 0;
}
struct Base {
VTable_Base* vptr;
int i;
};
struct Derived {
VTable_Base* vptr;
struct Base b;
int j;
};
int f_Base(struct Base * b) {
printf("base::f, i = %d\n", b->i);
return b->i;
}
int f_Derived(struct Derived* d) {
printf("derived::f, i = %d\n", d->b.i);
return d->b.i;
}
int f(struct Base * b) {
return b->vptr->f(b);
}
struct Base* make_Base() {
struct Base * b = malloc(sizeof(struct Base));
b->vptr = &vtable_base;
return b;
}
struct Derived* make_Derived() {
struct Derived * d = malloc(sizeof(struct Derived));
d->vptr = &vtable_derived;
return d;
}
int main() {
vptr_init();
struct Derived *d = make_Derived();
d->b.i = 10;
f((struct Base *)d); //derived::f, i = 10
free(d);
struct Base *b = make_Base();
b->i = 15;
f(b); //base::f, i = 15
free(b);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment