Is there a way to have some kind of default constructor (like a C++ one) for C user types defined with a structure?
I already have a macro which works like a fast in
Basically, C++ creates lists of pointers which contain the addresses of methods. This list is called a class definition (there is some more data in the class def, but we ignore that for now).
A common pattern to have "classes" in pure C is to define a "struct class". One of the fields of the struct is a factory function which returns "instances" of the class. I suggest to use a macro to hide the casts:
typedef struct __class * class;
typedef void (*ctor_ptr)(class);
struct class {
char * name;
ctor_ptr ctor;
... destructor and other stuff ...
}
#define NEW(clz) ((struct something *)(((struct class *)clz)->ctor(clz)))
Now, you can define the classes you have by creating structures of type "struct class" for each class you have and then call the constructor stored in them. The same goes for the destructor, etc.
If you want methods for your instances, must put them into the class structures and keep a pointer to the class in the instance struct:
#define NEW_SOMETHING() ((struct something *)NEW(&something_definition))
#define METHOD(inst, arg) ((struct something_class *)(((struct something *)inst)->clz)->method(inst, arg))
NEW_SOMETHING will create a new instance of "something" using the class definition stored in the structure something_definition. METHOD will invoke a "method" on this instance. Note that for real code, you will want to check that inst is actually an instance of something (compare the class pointers, something like that).
To have inheritance is a bit tricky and left as an exercise for the reader.
Note that you can do everything you can do in C++ in pure C. A C++ compiler does not magically replace your CPU with something else. It just takes a lot more code to do it.
If you want to look at an example, check out glib (part of the Gtk+ project).