Search code examples
cconstructor

Default constructor in C


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 initializer (like the one for pthread_mutex) but I wanted to know if you can by any chance have some (or all) fields of a struct filled at declaration.

For instance, with the pthread_mutex example, I would like

pthread_mutex_t my_mutex;

to have the same effect as

pthread_mutex_t my_mutex = PTHREAD_MUTEX_INITIALIZER;

Solution

  • You can create initializer functions that take a pointer to a structure. This was common practice.

    Also functions that create a struct and initialize it (like a factory) - so there is never a time where the struct is "uninitialized" in the "client" code. Of course - that assumes people follow the convention and use the "constructor"/factory...

    horrible pseudo code with NO error checking on malloc or free

    somestruct* somestruct_factory(/* per haps some initializer agrs? */)
    {
      malloc some stuff
      fill in some stuff
      return pointer to malloced stuff
    }
    
    
    void somestruct_destructor(somestruct*)
    {
      do cleanup stuff and also free pointer
      free(somestruct);
    }
    

    Someone will probably come along and explain how some early C++ preprocessors/compilers worked to do this all in C.