ben lemasurier
ben lemasurier

Reputation: 2592

Is it possible to emulate object methods in C?

Is it possible to emulate object methods in C? I'd like to be able self-reference a structure as a parameter to a member function argument e.g.:

struct foo {
    int a;
    int (*save)(struct foo *);
};

int
save_foo(struct foo *bar) {
    // do stuff.
}

struct foo *
create_foo() {
    struct foo *bar = malloc(sizeof(struct foo));
    bar->save = save_foo;

    return bar;
}

int
main() {
    struct foo *bar = create_foo();

    bar->a = 10;
    bar->save();
}

Where, bar->save(), actually calls save_foo(bar). Seems like a long shot, but it'd be pretty slick :)

Upvotes: 2

Views: 2541

Answers (5)

user3494898
user3494898

Reputation: 3

Yes, it's just awkward. I've implemented objects in Fortran77 using named common blocks.

In C, structs are probably the way to go. If you don't want to pass structs around, you could make them global and access them that way. Whatever work-around you choose, comment it well!

Sometimes one has to use C and doesn't have C++, Objective C, etc. available. I like Java and C# for OO programming, but sometimes you have to make do.

Upvotes: 0

Fred Foo
Fred Foo

Reputation: 363757

No, this is not possible. There are object-oriented libraries in C, but they pass the "this" object to the "method" explicitly as in

bar->save(bar);

See the Berkeley DB C API for an example of this style, but do consider using C++ or Objective-C if you want to do OO in a C-like language.

Upvotes: 4

Jim Buck
Jim Buck

Reputation: 20724

Yes, pass bar to the save function pointer, and you'll have what C++ does under-the-hood (invisibly passes this as the first parameter to the method). You can't get the this (aka bar) passed automatically in C.

Upvotes: 1

Zan Lynx
Zan Lynx

Reputation: 54345

The answer is "Yes."

The proof is that the first C++ compilers were not compilers at all. They simply translated C++ code into C code. The CFront compiler did this.

I see from the other answers that I probably misunderstood your question. No, the syntax you wrote in the question will not work in C. You'd need to write your own type of preprocessor/translator to convert the call from bar->save() to foo_save(bar) or even C3fooF4save(bar).

Upvotes: 1

a sad dude
a sad dude

Reputation: 2825

Basically, no. The reference to the function in C is simply a pointer to where it resides, and when you're calling it, you're just taking the pointer from the struct, jumping there and continuing execution without any knowledge about context or stack, so there's nowhere to take "this" from.

Upvotes: 2

Related Questions