From: Paul Brannan Date: 2002-09-25T00:01:13+09:00 Subject: Re: Object-Oriented struct Model in C On Tue, Sep 24, 2002 at 10:40:37PM +0900, William Djaja Tjokroaminata wrote: > typedef struct > { > /* pointer to parent */ > void *parentData; > void (*parentMarkFunc) (void*); > void (*parentFreeFunc) (void*); > > /* class-specific data */ > .... > } sClass_Any; This will work just fine. There's a little bit of extra run-time overhead from the extra pointer dereferencing you will do, and you will use a small amount of unnecessary memory from storing these pointers. If you want a bit of extra speed, then you can do the following... If you only need single inheritance and not multiple inheritance, then you could write: typedef struct { int x; int y; } Base; typedef struct { Base b; int z; } Derived; this would be analgous to: class Base attr_accessor :x attr_accessor :y end class Derived < Base attr_accessor :z end given a Derived, you can cast up to a Base without worrying about the exact structure of your class hierarchy: Derived *d = malloc(sizeof(Derived)); Base *b = (Base*)d; This is exactly how GTK+ does its inheritance (with the aid of some helper functions that add a little extra type safety). Also, note that you don't need a function pointer for the mark and free functions, unless each instance gets its own mark or free function. The mark and free functions should be associated with the object's class, not the instance of the class. With a good naming system, some macros, and the ## operator, you can almost hide them completely. Paul