How to define the constructor in C

advertisements

How can one create a Haskell/C++ style constructor in C? Also, once I have this new object how can I define operations in it (such as LinkedList/Tree)?


C has no language support for objected-oriented concepts such as constructors.

You could manually implement this, along the lines of:

typedef struct
{
    int field1;
    int field2;
} MyObject;

MyObject *MyObject_new(int field1, int field2)
{
    MyObject *p = malloc(sizeof(*p));
    if (p != NULL)
    {
        // "Initialise" fields
        p->field1 = field1;
        p->field2 = field2;
    }
    return p;
}

void MyObject_delete(MyObject *p)
{
    // Free other resources here too
    if (p != NULL)
    {
        free(p);
    }
}

void MyObject_doSomethingInteresting(const MyObject *p)
{
    printf("How interesting: %d\n", p->field1 * p->field2);
}

If you want to get really advanced, you can use hideously-complex macros and function pointers to emulate polymorphism and all sorts (at the expense of type-safety); see this book.

See also this question.

See also this FAQ answer if you're interested in compiling object-oriented C++ into C.