Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct base base_t;
- typedef struct child child_t;
- #define INIT() \
- base_t base; \
- child_t child; \
- printf("Init done...\n");
- #define NEW(a) _Generic((a), \
- base_t: base_new(), \
- child_t: child_new())
- #define NEW_1(a, b) _Generic((a), \
- base_t: base_new_1(b), \
- child_t: child_new())
- typedef struct base{
- int (*getId)(void* self);
- void (*free)(void* self);
- int id;
- } base_t;
- int getId(void* self){return ((base_t*)self)->id;}
- void base_free(void* bse){base_t* bs = (base_t*)bse; free(bs);}
- base_t* base_new(){
- base_t *res = malloc(sizeof(base_t));
- res->getId = getId;
- res->free = base_free;
- return res;
- }
- base_t* base_new_1(int id){
- base_t *res = malloc(sizeof(base_t));
- res->getId = getId;
- res->free = base_free;
- res->id = id;
- return res;
- }
- typedef struct child{
- int (*getId)(void* self);
- void (*free)(void* self);
- base_t *super;
- char name[10];
- } child_t;
- int getChildId(void* self){ return ((child_t*)self)->super->id;}
- void child_free(void* bse){
- child_t* chld = (child_t*)bse;
- chld->super->free(chld->super);
- free(chld);
- }
- child_t* child_new(){
- child_t* chld = malloc(sizeof(child_t));
- chld->super = base_new();
- chld->getId = getChildId;
- chld->free = child_free;
- return chld;
- }
- int main(int argc, char **argv){
- INIT(); //init base child for constructors
- base_t *bse = NEW_1(base, 2); //constructor
- child_t *chld;
- chld = NEW(child); //constructor
- chld->name[0] = '1';
- chld->super->id = 1;
- const int n = 3;
- void* mass[3] = {bse, chld, NEW_1(base, 10)};
- for (int i=0; i<n; i++){
- //int id = ((base_t*)mass[i])->getId(mass[i]); //Polymorphism
- int id = ((child_t*)mass[i])->getId(mass[i]); //Polymorphism
- printf("id =%i\n", id);
- }
- chld->free(chld);
- bse->free(bse);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement