Consider the following Python (3.x) code:
class Foo(object):
def bar(self):
pass
foo = Foo()
How to write the same functionalit
You can't! C does not have "classes", it only has struct
s. And a struct
cannot have code (methods or functions).
You can, however, fake it with function pointers:
/* struct object has 1 member, namely a pointer to a function */
struct object {
int (*class)(void);
};
/* create a variable of type `struct object` and call it `new` */
struct object new;
/* make its `class` member point to the `rand()` function */
new.class = rand;
/* now call the "object method" */
new.class();