Created
February 16, 2018 16:21
-
-
Save anon767/d0be260e5140eaa69366a1e4a44a67fe to your computer and use it in GitHub Desktop.
oop 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 <cstdio> | |
typedef struct { | |
int age; | |
char *name; | |
void (*eat)(const void *self); | |
} Animal; | |
void eat(const void *animal) { | |
printf("%s is eating\n", ((Animal *) animal)->name); | |
} | |
Animal * new_Animal(int age, char *name) { | |
Animal *object = (Animal *) malloc(sizeof(Animal)); | |
object->age = age; | |
object->name = name; | |
object->eat = eat; | |
return object; | |
} | |
typedef struct { | |
Animal base; | |
void (*fly)(const void *self); | |
} Bird; | |
void fly(const void *animal) { | |
printf("%s is flying\n", ((Animal *) animal)->name); | |
} | |
Bird * new_Bird(int age, char *name) { | |
Animal *object = (Animal *) malloc(sizeof(Animal)); | |
object->age = age; | |
object->name = name; | |
object->eat = eat; | |
Bird * bird = (Bird *) malloc(sizeof(Bird)); | |
bird->base = *object; | |
bird->fly = &fly; | |
return bird; | |
} | |
int main() { | |
Bird * object = new_Bird(18,"tom"); | |
((Animal *)object)->eat(object); | |
((Bird *)object)->fly(object); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment