Created
September 9, 2011 09:16
-
-
Save nooga/1205816 to your computer and use it in GitHub Desktop.
An attempt to mimic OOP syntax in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
// How it should look like: | |
/** | |
class Point { | |
int x,y; | |
new(int, int) {...}; | |
void moveBy(Point) {...}; | |
void print() {...}; | |
}; | |
**/ | |
// Fields and methods | |
typedef struct tPoint { | |
int x,y; | |
void (*moveBy)(struct tPoint*, struct tPoint*); | |
void (*print)(struct tPoint*); | |
} TPoint; | |
void Point_moveBy(TPoint* this, TPoint* that) { | |
this->x += that->x; | |
this->y += that->y; | |
} | |
void Point_print(TPoint* this) { | |
printf("(%d %d)\n",this->x, this->y); | |
} | |
TPoint* Point_new(int a, int b) { | |
TPoint* r = (TPoint*)malloc(sizeof(TPoint)); | |
r->x = a; | |
r->y = b; | |
r->moveBy = &Point_moveBy; | |
r->print = &Point_print; | |
return r; | |
} | |
// Static methods | |
struct { | |
TPoint* (*new)(int,int); | |
} Point = {&Point_new}; | |
int main (int argc, char const *argv[]) | |
{ | |
TPoint* a = Point.new(1,2); | |
TPoint* b = Point.new(2,3); | |
a->moveBy(a, b); | |
a->print(a); | |
b->print(b); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment