Advertisement
xeritt

OOP in C simple example

Feb 19th, 2021
1,574
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.28 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. typedef struct base base_t;
  4. typedef struct child child_t;
  5. typedef struct base{
  6.     int (*getId)(void* self);
  7.     void (*free)(void* self);
  8.     int id;
  9. } base_t;
  10. int getId(void* self){
  11.     return ((base_t*)self)->id;
  12. }
  13. void base_free(void* bse){base_t* bs = (base_t*)bse; free(bs);}
  14. base_t * base_new(){
  15.     base_t *res = malloc(sizeof(base_t));
  16.     res->getId = getId;
  17.     res->free = base_free;
  18.     return res;
  19. }
  20. typedef struct child{
  21.     int (*getId)(void* self);
  22.     void (*free)(void* self);
  23.     base_t *super;
  24.     char name[10];
  25. } child_t;
  26.  
  27. int getChildId(void* self){
  28.     return ((child_t*)self)->super->id;
  29. }
  30.  
  31. void child_free(void* bse){
  32.     child_t* chld = (child_t*)bse;
  33.     chld->super->free(chld->super);
  34.     free(chld);
  35. }
  36.  
  37. child_t* child_new(){
  38.     child_t* chld = malloc(sizeof(child_t));
  39.     chld->super = base_new();
  40.     chld->getId = getChildId;
  41.     chld->free = child_free;
  42.     return chld;
  43. }
  44.  
  45. int main(int argc, char **argv){
  46.     base_t *bse = base_new();
  47.     bse->id = 0;
  48.     child_t *child;
  49.     child = child_new();
  50.     child->name[0] = '1';
  51.     child->super->id = 1;
  52.     int n = 2;
  53.     void* mass[2] = {bse, child};
  54.     for (int i=0; i<n; i++){
  55.         int id = ((base_t*)mass[i])->getId(mass[i]);
  56.         printf("id =%i\n", id);
  57.     }
  58.     child->free(child);
  59.     bse->free(bse);
  60.     return 0;
  61. }
  62.  
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement