/* ** $Id: oldobj.c 802 2008-03-01 19:26:43Z phf $ ** ** A simple way to fake objects through structs and ** function pointers. Very few people use stuff like ** this, except maybe to define certain interfaces ** for others to "plug into". See the spam filter ** code you read early in the semester and the way ** its database interface was set up. :-) ** ** Sorry, no comments, but you can look stuff like ** this up online. Here are a few pointers: ** ** http://www.cs.usfca.edu/~parrt/course/652/lectures/polymorphism.html ** http://onestepback.org/articles/poly/ ** http://www.d.umn.edu/~gshute/softeng/ooC/ooC.html ** ** And let's not forget the magnum opus of this kind ** of hacking: ** ** http://ldeniau.web.cern.ch/ldeniau/html/oopc.html ** ** We'll just switch to C++ instead, but it's nice to ** know how the basic OO stuff works under the hood... */ #include #include typedef struct rectangle* Rectangle; struct rectangle { int width; int height; int (*area)( Rectangle ); }; int rectangle_area( Rectangle this ) { return this->width * this->height; } Rectangle make_rectangle( int width, int height ) { Rectangle new = malloc( sizeof( struct rectangle ) ); new->width = width; new->height = height; new->area = rectangle_area; return new; } int insane_area( Rectangle this ) { return this->width * this->height * 4 - 27; } Rectangle make_insane( int width, int height ) { Rectangle new = malloc( sizeof( struct rectangle ) ); new->width = width; new->height = height; new->area = insane_area; return new; } int area( Rectangle r ) { return (*r->area)(r); // "polymorphic" call! } int main( void ) { // Rectangle r = new Rectangle(10,20); Rectangle r = make_rectangle( 10, 20 ); Rectangle q = make_insane( 10, 20 ); printf( "%d\n", r->width); // printf( "%d\n", r.area() ); printf( "%d\n", (*r->area)(r) ); printf( "%d\n", (*q->area)(q) ); printf( "%d\n", area(r) ); printf( "%d\n", area(q) ); return EXIT_SUCCESS; }