fork download
  1. #include <stdio.h>
  2.  
  3. typedef struct {
  4. int (*myFunc1) ();
  5. int (*myFunc2) ();
  6. } VTable;
  7.  
  8. typedef struct {
  9. const VTable* _vtable;
  10. int a, b;
  11. } Base;
  12.  
  13. typedef struct {
  14. Base _base;
  15. } Derived1;
  16.  
  17. typedef struct {
  18. Base _base;
  19. } Derived2;
  20.  
  21. int Derived1_myFunc1 () {
  22. return 1;
  23. }
  24.  
  25. int Derived1_myFunc2 () {
  26. return 2;
  27. }
  28.  
  29. int Derived2_myFunc1 () {
  30. return 3;
  31. }
  32.  
  33. int Derived2_myFunc2 () {
  34. return 4;
  35. }
  36.  
  37.  
  38. const VTable vtableDerived1 = { &Derived1_myFunc1, &Derived1_myFunc2 };
  39. const VTable vtableDerived2 = { &Derived2_myFunc1, &Derived2_myFunc2 };
  40.  
  41. void Derived1_Construct (Derived1* instance) {
  42. instance->_base._vtable = &vtableDerived1;
  43. }
  44.  
  45. void Derived2_Construct (Derived2* instance) {
  46. instance->_base._vtable = &vtableDerived2;
  47. }
  48.  
  49. /// -----
  50.  
  51. void someFunction (Base* base) {
  52. int x = (base->_vtable->myFunc1) ();
  53. int y = (base->_vtable->myFunc2) ();
  54.  
  55. printf ("%d\n", x*y);
  56. }
  57.  
  58. int main () {
  59. Derived1 d1;
  60. Derived1_Construct (&d1);
  61.  
  62. Derived2 d2;
  63. Derived2_Construct (&d2);
  64.  
  65. someFunction (&d1._base);
  66. someFunction (&d2._base);
  67. }
Success #stdin #stdout 0s 2248KB
stdin
Standard input is empty
stdout
2
12