fork download
  1. #include <stdio.h>
  2.  
  3. struct point;
  4. struct point3d;
  5. struct point_it_vtbl;
  6.  
  7. int point_calc(struct point*);
  8. int point3d_calc(struct point*);
  9. void point_init(struct point*, int, int);
  10. void point3d_init(struct point3d*, int, int, int);
  11. void point_print(struct point*);
  12. void point3d_print(struct point*);
  13.  
  14.  
  15. struct point_it_vtbl {
  16. int (*calc)(struct point*);
  17. void (*print)(struct point*);
  18. }
  19. point_vtbl = { &point_calc, &point_print },
  20. point3d_vtbl = { &point3d_calc, &point3d_print }
  21. ;
  22.  
  23. struct point {
  24. struct point_it_vtbl* vtbl;
  25. int x, y;
  26. };
  27.  
  28. struct point3d {
  29. struct point base;
  30. int z;
  31. };
  32.  
  33.  
  34. int point_calc(struct point* this) {
  35. return this->x * this->y;
  36. }
  37.  
  38. int point3d_calc(struct point* this) {
  39. return point_calc(this) * (*(struct point3d*)this).z;
  40. }
  41.  
  42. void point_print(struct point* this) {
  43. printf("%i, %i", this->x, this->y);
  44. }
  45.  
  46. void point3d_print(struct point* this) {
  47. point_print(this);
  48. printf(", %i", (*(struct point3d*)this).z);
  49. }
  50.  
  51. void test(struct point* p) {
  52. p->vtbl->print(p);
  53. }
  54.  
  55. int main(void) {
  56. struct point3d t = { { &point3d_vtbl, 6, 3 } , 9 };
  57. test((struct point*)&t);
  58. printf(" %i", t.base.vtbl->calc(&t.base));
  59. return 0;
  60. }
Success #stdin #stdout 0s 9416KB
stdin
Standard input is empty
stdout
6, 3, 9 162