Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #define new(Obj,...) Obj##_##new((Obj*)malloc(sizeof(Obj)), ##__VA_ARGS__);
- // --------- Class A ---------- //
- // Definition
- typedef struct _A {
- void (*method)();
- int x;
- } A;
- // Method
- void A_method(A* self) {
- printf("Method invoked in A\n");
- }
- // Constructor
- A* A_new(A* self) {
- self->x = 2;
- self->method = A_method;
- return self;
- }
- // -------- Class B ----------- //
- // Definition
- typedef struct _B {
- // Inheritance (must be first)
- A super;
- // New fields
- int y;
- } B;
- // Method
- void B_method(B* self) {
- printf("This is method B\n");
- }
- // Constructor
- B* B_new(B* self) {
- // Superclass constructor
- A_new((A*)self);
- // Overrides
- self->super.method = B_method;
- return self;
- }
- // ---------- Main ----------- //
- int main() {
- A* a = (A*)new(B);
- a->method(a);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement