Created
July 26, 2016 00:47
-
-
Save anthony-y/0e7331126aab25cf55d191a248e392ed to your computer and use it in GitHub Desktop.
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 <stdio.h> | |
#include <stdlib.h> | |
typedef struct _Animal { void (**vtable)(); } Animal; | |
typedef struct _Dog { Animal base; } Dog; | |
typedef struct _Cat { Animal base; } Cat; | |
// To strings | |
void animal_to_string(Animal *this) { printf(" Base animal\n"); } | |
void dog_to_string (Dog *this) { printf(" Dog\n"); } | |
void cat_to_string (Cat *this) { printf(" Cat\n"); } | |
// Actions | |
void animal_action(Animal *this) { printf(" ...\n"); } | |
void dog_action (Dog *this) { printf(" Bark!\n"); } | |
void cat_action (Cat *this) { printf(" Meow!\n"); } | |
enum { Call_To_String, Call_Action }; | |
void (*Animal_Vtable[])() = { &animal_to_string, &animal_action }; | |
void (*Dog_Vtable[])() = { &dog_to_string, &dog_action }; | |
void (*Cat_Vtable[])() = { &cat_to_string, &cat_action }; | |
void to_string(Animal *this) { this->vtable[Call_To_String](this); } | |
void action (Animal *this) { this->vtable[Call_Action](this); } | |
int main(int argc, char **argv) | |
{ | |
Animal a = { Animal_Vtable }; | |
Dog d = { Dog_Vtable }; | |
Cat c = { Cat_Vtable }; | |
Animal *animal = (Animal *)&a; | |
Animal *dog = (Animal *)&d; | |
Animal *cat = (Animal *)&c; | |
printf("\n To String\n"); | |
printf(" ----------\n"); | |
to_string(animal); | |
to_string(dog); | |
to_string(cat); | |
printf("\n Actions\n"); | |
printf(" --------\n"); | |
action(animal); | |
action(dog); | |
action(cat); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment