Tuesday, May 10, 2011

OOPinC_constructor(&reader);

Hello and welcome to the Object Oriented Programming in C blog. My name is John Robertson, and I am a professional software engineer and Linux guru located in the southeastern United States of America. The purpose of this blog is to share and extend a specific set of highly productive object oriented programming techniques in C which I have developed over the last 14 years.

It all started back in 1997 when I contracted to write a warehouse inventory application on a hand-held Psion 16 bit computing platform. While my roots are in C, I had been programming in C++ for several years, and was disappointed to discover that no C++ compiler was available for the Psion platform at that time. My choices were Psion's version of Basic, or C, so I chose C.

After programming in C++ for several years I had grown accustomed to the formal object oriented constructs of C++. Remembering that C++ started out as a preprocessor to C, I began to contemplate ways that object oriented programming can be coded in C such that the code is both versatile and legible. The Psion inventory application project went very well, and since then I find myself drawn back to these techniques time and time again with excellent results.

So, let's get started with a constructor for a class "CLASS" in C:

typedef struct _CLASS {
  /* members go here */
} CLASS;

CLASS*
CLASS_constructor(CLASS *self)
{
  CLASS *rtn= NULL;
  /* initialize members. If something goes wrong,
   * goto abort, which will cause
   * the constructor to return NULL.
   */
  rtn= self; /* Assign successful return value */

abort:
  return rtn;
}


The address of the instance to be initialized is passed in as self, which can be located on the stack, on the heap, or in the static data segment. Furthermore, success can be determined by examining the constructor's return value.

In my next post I will present a CLASS_create() macro which provides the functionality of the C++ new operator, with some extra goodies.

No comments:

Post a Comment