Advertisement
Guest User

Untitled

a guest
Apr 10th, 2018
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.02 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct foo {
  5.   void (*print)(struct foo *, FILE *);
  6. };
  7.  
  8. void
  9. print_foo(struct foo *obj, FILE *f)
  10. {
  11.   obj->print(obj, f);
  12. }
  13.  
  14. struct bar {
  15.   struct foo vtable;
  16.   int n;
  17. };
  18.  
  19. void print_bar(struct foo *obj, FILE *f)
  20. {
  21.   struct bar *b = (struct bar *)obj;
  22.   fprintf(f, "bar: %d\n", b->n);
  23. }
  24.  
  25. struct foo *
  26. make_bar(int n) {
  27.   struct bar *b;
  28.   b = malloc(sizeof *b);
  29.   b->vtable.print = print_bar;
  30.   b->n = n;
  31.   return (struct foo *)b;
  32. }
  33.  
  34. struct baz {
  35.   struct foo vtable;
  36.   double d;
  37. };
  38.  
  39. void print_baz(struct foo *obj, FILE *f)
  40. {
  41.   struct baz *b = (struct baz *)obj;
  42.   fprintf(f, "baz: %f\n", b->d);
  43.  
  44. }
  45.  
  46. struct foo *
  47. make_baz(double d) {
  48.   struct baz *b;
  49.   b = malloc(sizeof *b);
  50.   b->vtable.print = print_baz;
  51.   b->d = d;
  52.   return (struct foo *)b;
  53. }
  54.  
  55. int
  56. main(void)
  57. {
  58.   struct foo *objects[2];
  59.  
  60.   objects[0] = make_bar(1);
  61.   objects[1] = make_baz(2.0);
  62.  
  63.   print_foo(objects[0], stdout);
  64.   print_foo(objects[1], stdout);
  65.  
  66.   return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement