Friday, October 1, 2010

Object Oriented C

So, thanks to blocks, Apple's new extension to C, you can now do basic object-orientation. Have a look over at github for a short example on how to do it.

To break it down, an object is a struct, which contains both fields and blocks which act as the object's methods.
typedef struct {
    Object super;
    char *_value;
    const char *(^getValue)();
    void (^setValue)( const char * );
} String;
This creates a String object which inherits from Object and has a field _value, and methods getValue and setValue.

Because this String's first field is an Object, it can be safely casted to one (upwards casting).

More to come... maybe.

4 comments:

Unknown said...

What is the advantage of using Blocks to declare those methods as opposed to Function Pointers?

Russ said...

Blocks allow you to have a "this" reference inside the body of your method without having to pass "this" as the first parameter to every function call.

Unknown said...

I see, that's pretty impressive.

The only other issue I see here though is that it means every instance of that struct will have an additional 4 (or 8, depending on what it's being built for) bytes for each method.

Russ said...

You mean in order to store the reference to "this"?

If the reference were passed in to the struct, you would still be using those additional 4 (or 8) bytes to store the "this" reference, but the space used would be separated from the object.