Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdint.h>
- #include <stdlib.h>
- #define exec(Object, Method) Object->table.Method()
- typedef int32_t int32;
- typedef uint8_t uint8;
- typedef void (*set_fcn_ptr) (void*, int32);
- typedef int32 (*get_fcn_ptr) (void*);
- typedef void (*display_fcn_ptr) (void);
- typedef struct {
- set_fcn_ptr set_x;
- get_fcn_ptr get_x;
- set_fcn_ptr set_y;
- get_fcn_ptr get_y;
- display_fcn_ptr display;
- } VTable;
- /*
- ================================================================================
- */
- typedef struct {
- VTable table;
- int32 x;
- int32 y;
- } Shape;
- void shape_set_x(Shape* shape, int32 x) { shape->x = x; }
- void shape_set_y(Shape* shape, int32 y) { shape->y = y; }
- int32 shape_get_x(Shape* shape) { return shape->x; }
- int32 shape_get_y(Shape* shape) { return shape->y; }
- void shape_display(Shape* shape) { fputs("Shape", stdout); }
- Shape* make_shape(int32 x, int32 y)
- {
- Shape* shape = malloc(sizeof(Shape));
- VTable* vtable = &shape->table;
- vtable->set_x = shape_set_x;
- vtable->set_y = shape_set_y;
- vtable->get_x = shape_get_x;
- vtable->get_y = shape_get_y;
- vtable->display = shape_display;
- shape->x = x;
- shape->y = y;
- }
- /*
- ================================================================================
- */
- typedef struct {
- Shape base;
- size_t width;
- size_t height;
- } Rectangle;
- void rect_set_x(Rectangle* rect, int32 x) { rect->base.x = x; }
- void rect_set_y(Rectangle* rect, int32 y) { rect->base.y = y; }
- int32 rect_get_x(Rectangle* rect) { return rect->base.x; }
- int32 rect_get_y(Rectangle* rect) { return rect->base.y; }
- void rect_display(Rectangle* rect) { fputs("Rectangle", stdout); }
- Rectangle* make_rectangle(int32 x, int32 y, size_t w, size_t h)
- {
- Rectangle* rect = malloc(sizeof(Rectangle));
- VTable* vtable = &rect->base.table;
- vtable->set_x = rect_set_x;
- vtable->set_y = rect_set_y;
- vtable->get_x = rect_get_x;
- vtable->get_y = rect_get_y;
- vtable->display = rect_display;
- rect->base.x = x;
- rect->base.y = y;
- rect->width = w;
- rect->height = h;
- }
- /*
- ================================================================================
- */
- int main()
- {
- Shape* shapes[4];
- shapes[0] = make_shape(3, 5);
- shapes[1] = make_rectangle(7, 2, 10, 10);
- shapes[2] = make_shape(10, 2);
- shapes[3] = make_rectangle(0, 7, 50, 50);
- for (uint8 i = 0; i < 4; ++i) {
- exec(shapes[i], display);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement