Advertisement
Guest User

Untitled

a guest
Jun 22nd, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.90 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #define new(Obj,...) Obj##_##new((Obj*)malloc(sizeof(Obj)), ##__VA_ARGS__);
  5.  
  6. // --------- Class A ---------- //
  7. // Definition
  8. typedef struct _A {
  9.    void (*method)();
  10.    int x;
  11. } A;
  12.  
  13. // Method
  14. void A_method(A* self) {
  15.    printf("Method invoked in A\n");
  16. }
  17.  
  18. // Constructor
  19. A* A_new(A* self) {
  20.    self->x = 2;
  21.    self->method = A_method;
  22.    return self;
  23. }
  24.  
  25. // -------- Class B ----------- //
  26. // Definition
  27. typedef struct _B {
  28.    // Inheritance (must be first)
  29.    A super;
  30.  
  31.    // New fields
  32.    int y;
  33. } B;
  34.  
  35. // Method
  36. void B_method(B* self) {
  37.    printf("This is method B\n");
  38. }
  39.  
  40. // Constructor
  41. B* B_new(B* self) {
  42.    // Superclass constructor
  43.    A_new((A*)self);
  44.  
  45.    // Overrides
  46.    self->super.method = B_method;
  47.    return self;
  48. }
  49.  
  50. // ---------- Main ----------- //
  51. int main() {
  52.    A* a = (A*)new(B);
  53.    a->method(a);
  54.    return 0;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement