design - How do you implement a class in C? -
assuming have use c (no c++ or object oriented compilers) , don't have dynamic memory allocation, techniques can use implement class, or approximation of class? idea isolate "class" separate file? assume can preallocate memory assuming fixed number of instances, or defining reference each object constant before compile time. feel free make assumptions oop concept need implement (it vary) , suggest best method each.
restrictions:
- i have use c , not oop because i'm writing code embedded system, , compiler , preexisting code base in c.
- there no dynamic memory allocation because don't have enough memory reasonably assume won't run out if start dynamically allocating it.
- the compilers work have no problems function pointers
that depends on exact "object-oriented" feature-set want have. if need stuff overloading and/or virtual methods, need include function pointers in structures:
typedef struct { float (*computearea)(const shapeclass *shape); } shapeclass; float shape_computearea(const shapeclass *shape) { return shape->computearea(shape); } this let implement class, "inheriting" base class, , implementing suitable function:
typedef struct { shapeclass shape; float width, height; } rectangleclass; static float rectangle_computearea(const shapeclass *shape) { const rectangleclass *rect = (const rectangleclass *) shape; return rect->width * rect->height; } this of course requires implement constructor, makes sure function pointer set up. you'd dynamically allocate memory instance, can let caller that, too:
void rectangle_new(rectangleclass *rect) { rect->width = rect->height = 0.f; rect->shape.computearea = rectangle_computearea; } if want several different constructors, have "decorate" function names, can't have more 1 rectangle_new() function:
void rectangle_new_with_lengths(rectangleclass *rect, float width, float height) { rectangle_new(rect); rect->width = width; rect->height = height; } here's basic example showing usage:
int main(void) { rectangleclass r1; rectangle_new_with_lengths(&r1, 4.f, 5.f); printf("rectangle r1's area %f units square\n", shape_computearea(&r1)); return 0; } i hope gives ideas, @ least. successful , rich object-oriented framework in c, glib's gobject library.
also note there's no explicit "class" being modelled above, each object has own method pointers bit more flexible you'd typically find in c++. also, costs memory. away stuffing method pointers in class structure, , invent way each object instance reference class.
Comments
Post a Comment