Default constructor in C

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.

Leave a Comment