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
C++ is different from C in this case in the respect that it has no "classes". However, C (as many other languages) can still be used for object oriented programming. In this case, your constructor can be a function that initializes a struct. This is the same as constructors (only a different syntax). Another difference is that you have to allocate the object using malloc() (or some variant). In C++ you would simlpy use the 'new' operator.
e.g. C++ code:
class A {
public:
A() { a = 0; }
int a;
};
int main()
{
A b;
A *c = new A;
return 0;
}
equivalent C code:
struct A {
int a;
};
void init_A_types(struct A* t)
{
t->a = 0;
}
int main()
{
struct A b;
struct A *c = malloc(sizeof(struct A));
init_A_types(&b);
init_A_types(c);
return 0;
}
the function 'init_A_types' functions as a constructor would in C++.