Disclaimer: I am a complete newbie with C, but I've been playing with it trying to mimic some features of classes. Ok, I know that if I want to go that way I should learn C++, but consider the following a little experiment.

Schreiner, in the book Object-oriented programming with ANSI-C suggests a way to use pointers to get object orientation features in C. I must admit I have only skimmed through the book, but I don't like his approach too much. Basically, he uses pointers to functions in order to arrange that

func(foo);

actually results in calling

foo.methods->func();

where foo.methods is a struct containing pointers to functions. The thing I do not like in this approach is that one has to have the global function foo anyway; that is, methods are not namespaced by the class they live in. My feeling is that this will soon lead to clutter: think two objects foo and bar, both having a method func but with a different number of parameters.

So I have tried to get something more fit to my taste. A first attempt is the following (I omit the declarations for sake of brevity)

#include <stdio.h>

//Instances of this struct will be my objects
struct foo {
    //Properties
    int bar;

    //Methods
    void (* print)(struct foo self);
    void (* printSum)(struct foo self, int delta);
};

//Here is the actual implementation of the methods
static void printFoo(struct foo self) {
    printf("This is bar: %d\n", self.bar);
}

static void printSumFoo(struct foo self, int delta) {
    printf("This is bar plus delta: %d\n", self.bar + delta);
}

//This is a sort of constructor
struct foo Foo(int bar) {
    struct foo foo = {
        .bar = bar,
        .print = &printFoo,
        .printSum = &printSumFoo
    };
    return foo;
}

//Finally, this is how one calls the methods
c oop
Edit
Report