xeritt

OOP in C simple example constructors

Feb 20th, 2021
485
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. typedef struct base base_t;
  4. typedef struct child child_t;
  5. #define INIT() \
  6.     base_t base; \
  7.     child_t child; \
  8.     printf("Init done...\n");
  9.  
  10. #define NEW(a) _Generic((a), \
  11.     base_t: base_new(), \
  12.     child_t: child_new())
  13.  
  14. #define NEW_1(a, b) _Generic((a), \
  15.     base_t: base_new_1(b), \
  16.     child_t: child_new())
  17.      
  18. typedef struct base{
  19.     int (*getId)(void* self);
  20.     void (*free)(void* self);
  21.     int id;
  22. } base_t;
  23.  
  24. int getId(void* self){return ((base_t*)self)->id;}
  25. void base_free(void* bse){base_t* bs = (base_t*)bse; free(bs);}
  26.  
  27. base_t* base_new(){
  28.     base_t *res = malloc(sizeof(base_t));
  29.     res->getId = getId;
  30.     res->free = base_free;
  31.     return res;
  32. }
  33.  
  34. base_t* base_new_1(int id){
  35.     base_t *res = malloc(sizeof(base_t));
  36.     res->getId = getId;
  37.     res->free = base_free;
  38.     res->id = id;
  39.     return res;
  40. }
  41.  
  42. typedef struct child{
  43.     int (*getId)(void* self);
  44.     void (*free)(void* self);
  45.     base_t *super;
  46.     char name[10];
  47. } child_t;
  48.  
  49. int getChildId(void* self){ return ((child_t*)self)->super->id;}
  50.  
  51. void child_free(void* bse){
  52.     child_t* chld = (child_t*)bse;
  53.     chld->super->free(chld->super);
  54.     free(chld);
  55. }
  56.  
  57. child_t* child_new(){
  58.     child_t* chld = malloc(sizeof(child_t));
  59.     chld->super = base_new();
  60.     chld->getId = getChildId;
  61.     chld->free = child_free;
  62.     return chld;
  63. }
  64.  
  65. int main(int argc, char **argv){
  66.     INIT(); //init base child for constructors
  67.     base_t *bse = NEW_1(base, 2); //constructor
  68.     child_t *chld;
  69.     chld = NEW(child); //constructor
  70.     chld->name[0] = '1';
  71.     chld->super->id = 1;
  72.     const int n = 3;
  73.     void* mass[3] = {bse, chld, NEW_1(base, 10)};
  74.     for (int i=0; i<n; i++){
  75.         //int id = ((base_t*)mass[i])->getId(mass[i]); //Polymorphism
  76.         int id = ((child_t*)mass[i])->getId(mass[i]); //Polymorphism
  77.         printf("id =%i\n", id);
  78.     }
  79.     chld->free(chld);
  80.     bse->free(bse);
  81.     return 0;
  82. }
  83.  
  84.  
RAW Paste Data