i was told objects can be created in C just like c++. Does anyone happen to have any examples of how this is done or any recommended resources on this :) thx

Recommended Answers

All 2 Replies

I've only skimmed through it in the past, but check out http://www.freetechbooks.com/object-oriented-programming-with-ansi-c-t551.html (free and legal download). It does a lot of preprocessing on the code.

Something you might be interested in, as I think it's at least peripherally related is the cfront system that converted C++ to C (see http://en.wikipedia.org/wiki/Cfront) for compilation in the early years of C++.

i was told objects can be created in C just like c++.

Objects are really just lumping data and functions that operate on the data into one package. In C you can't have member functions, but you can have pointers to functions:

#include <stdio.h>

typedef struct foo foo;

struct foo {
    int data;
    void (*add)(foo *self);
};

void foo_add(foo *self)
{
    ++self->data;
}

int main()
{
    foo obj = {0, foo_add};
    int i;

    for (i = 0; i < 10; i++) {
        obj.add(&obj);
        printf("%d\n", obj.data);
    }

    return 0;
}

The process is lower level than C++ in that you need to manually handle some of the things that C++ does for you, such as passing the this pointer to member functions and attaching member functions to each object on initialization.

Objects like this are easy. The complication is introduced when one wants to implement inheritance and polymorphism to C, which usually results in ridiculous abuse of the preprocessor. ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.