Created
August 9, 2021 22:16
-
-
Save hamzamuric/08499b297f0609f0ca52f1d50b5c382c to your computer and use it in GitHub Desktop.
Manual implementation of virtual dispatch and virtual tables in C.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
typedef struct Animal { | |
void (*say)(void *this); | |
} Animal; | |
typedef struct Cat { | |
Animal *vptr; | |
char *name; | |
int age; | |
} Cat; | |
typedef struct Dog { | |
Animal *vptr; | |
char *name; | |
char *nickname; | |
} Dog; | |
void cat_say(Cat *this) { | |
printf("I'm cat %s and im %d yrs old\n", this->name, this->age); | |
} | |
void dog_say(Dog *this) { | |
printf("I'm dog %s but they call me %s\n", this->name, this->nickname); | |
} | |
Animal cat_vtable = { .say = (void*)cat_say }; | |
Animal dog_vtable = { .say = (void*)dog_say }; | |
void cat_init(Cat *this, char* name, int age) { | |
this->vptr = &cat_vtable; | |
this->name = name; | |
this->age = age; | |
} | |
void dog_init(Dog *this, char *name, char *nickname) { | |
this->vptr = &dog_vtable; | |
this->name = name; | |
this->nickname = nickname; | |
} | |
int main() { | |
Cat *c = (Cat*)malloc(sizeof(Cat)); | |
Dog *d = (Dog*)malloc(sizeof(Dog)); | |
cat_init(c, "Bella", 2); | |
dog_init(d, "Jasper", "Jas"); | |
Animal** animals[2] = { (Animal**)c, (Animal**)d }; | |
for (int i = 0; i < 2; i++) { | |
Animal **a = animals[i]; | |
(*a)->say(a); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment