Skip to content

Instantly share code, notes, and snippets.

@nooga
Created September 9, 2011 09:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nooga/1205816 to your computer and use it in GitHub Desktop.
Save nooga/1205816 to your computer and use it in GitHub Desktop.
An attempt to mimic OOP syntax in C
#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