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
#ifndef OBJECT_H_ | |
#define OBJECT_H_ | |
#define OBJECT_INHERIT \ | |
void *(**vtable)(); \ | |
const char *name; | |
typedef struct object { | |
OBJECT_INHERIT | |
} OBJECT; | |
enum | |
{ | |
CALL__print | |
}; | |
extern void *(*OBJECT__vtable[])(); | |
static void OBJECT__print(OBJECT *object); | |
extern OBJECT* new_object(const char *); | |
extern void print(void *object); | |
#endif | |
#ifndef PERSON_H_ | |
#define PERSON_H_ | |
#include "object.h" | |
typedef struct person { | |
OBJECT_INHERIT | |
int day; | |
int month; | |
int year; | |
} PERSON; | |
extern void *(*PERSON__vtable[])(); | |
extern PERSON *new_person(const char *, int, int, int); | |
static void PERSON__print(PERSON *); | |
#endif | |
#include "object.h" | |
#include <stdlib.h> | |
#include <stdio.h> | |
void *(*OBJECT__vtable[])() = {(void*(*)())&OBJECT__print}; | |
void OBJECT__print(OBJECT *this) | |
{ | |
printf("(OBJECT) { name : \"%s\" }\n", this->name); | |
} | |
void print(void *object) | |
{ | |
((OBJECT *)object)->vtable[CALL__print]((OBJECT *)object); | |
} | |
OBJECT* new_object(const char *name) | |
{ | |
OBJECT *object = (OBJECT *)malloc(sizeof(OBJECT)); | |
object->vtable = OBJECT__vtable; | |
object->name = name; | |
return object; | |
} | |
#include "person.h" | |
#include "object.h" | |
#include <stdlib.h> | |
#include <stdio.h> | |
void *(*PERSON__vtable[])() = {(void*(*)())&PERSON__print}; | |
PERSON *new_person(const char *name, int day, int month, int year) | |
{ | |
OBJECT *super; | |
PERSON *this; | |
super = new_object(name); | |
this = (PERSON *)realloc(super, sizeof(PERSON)); | |
this->vtable = PERSON__vtable; | |
this->day = day; | |
this->month = month; | |
this->year = year; | |
return this; | |
} | |
void PERSON__print(PERSON *this) | |
{ | |
printf("(PERSON) { name : \"%s\", day : %d, month : %d, year : %d }\n", | |
this->name, this->day, this->month, this->year); | |
} | |
#include "object.h" | |
#include "person.h" | |
#include <stdlib.h> | |
int main(int argc, char const* argv[]) | |
{ | |
OBJECT *spoon; | |
PERSON *arian; | |
spoon = new_object("Spoon"); | |
if(spoon == NULL) return 1; | |
arian = new_person("Arian", 28, 11, 1993); | |
if(arian == NULL) return 1; | |
print(spoon); | |
print(arian); | |
free(spoon); | |
free(arian); | |
return 0; | |
/* OUTPUT | |
(OBJECT) { name : "Spoon" } | |
(PERSON) { name : "Arian", day : 28, month : 11, year : 1993 } | |
*/ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment