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;
- 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;
- }
- 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){
- base_t *bse = base_new();
- bse->id = 0;
- child_t *child;
- child = child_new();
- child->name[0] = '1';
- child->super->id = 1;
- int n = 2;
- void* mass[2] = {bse, child};
- for (int i=0; i<n; i++){
- int id = ((base_t*)mass[i])->getId(mass[i]);
- printf("id =%i\n", id);
- }
- child->free(child);
- bse->free(bse);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement