[clug] Object-Oriented C?

Martin Pool mbp at sourcefrog.net
Wed Feb 22 03:04:31 GMT 2006


On Wed, 2006-02-22 at 13:17 +1100, Paul Wayper wrote:

> Anyway, I've heard several people talk about writing C in an
> object-oriented way.  I've done the simplest thing here, which is that
> each function takes a PInfo pointer as its first argument, which is the
> 'object' that it operates on.  This isn't ver object-oriented at all, in
> that you have to constantly tell the 'method' which object to orient
> itself toward.  The more complex way would be to have a structure a bit
> like this:
> 
> typedef struct object_struct {
>     int public_property;
>     int (*method)(int value);
> } Object;
> 
> Thus if you had "Object *foo" you could call foo->method(42).  When you
> get a new object the 'constructor' would put the pointers to the actual
> methods into the Object struct so that the call was correct.  The
> problem is, of course, that the actual method function enters and sees -
> what?  No context, no object, no nothing.  Implicit in the 'constructor'
> of object-oriented actions is the idea that the method call gets told
> _which_ object it's operating on - Perl does it semi-explicitly by
> assuming that the first parameter is a reference to the object.

You need to either do foo->method(foo, 42), or hide this behind a
facade.  For example gtk/gobject make a lot of use of 

  g_object_method(object, arg)

which internally checks the object is of the right type and then calls
it.

Many method calls don't need to be virtual - ie won't be implemented
differently in subclasses.  Indeed many classes won't be subclassed at
all.  Then there's no need to dispatch through a function pointer; in
this kind of situation OO C can be quite palatable.  If you are going to
have extensive subclassing or virtual dispatch maybe you should use C++
or a framework like gobject. 

-- 
Martin

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 191 bytes
Desc: This is a digitally signed message part
Url : http://lists.samba.org/archive/linux/attachments/20060222/5fa4e21b/attachment.bin


More information about the linux mailing list