1

Possible Duplicates:
Object oriented programming in C
Can you write object oriented code in C?

Hi

I know there are some coding styles for pure C that mimics object-oriented programming : "method call"(functions) on "objects"(struct) .c and .h organisation, and so on...

What are your habits about that ?

Is there some good tutorial on that ? Or examples ?

Community
  • 1
  • 1
JCLL
  • 5,379
  • 5
  • 44
  • 64
  • Long but good: http://www.planetpdf.com/codecuts/pdfs/ooc.pdf – Chris Lutz Feb 04 '11 at 09:47
  • Many duplicates, e.g. [Object oriented programming in C](http://stackoverflow.com/questions/2181079/object-oriented-programming-in-c), [Experiment: Object Oriented C?](http://stackoverflow.com/questions/4103704/experiment-object-oriented-c), [Can you write object oriented code in C?](http://stackoverflow.com/questions/351733/can-you-write-object-oriented-code-in-c), etc... – Paul R Feb 04 '11 at 09:48
  • Look at http://www.ijg.org/ . It does not even look as C. – ruslik Feb 04 '11 at 10:32
  • Paul R, so do you advise me to delete this question ? – JCLL Feb 04 '11 at 10:36
  • Check out [COOP](https://github.com/ShmuelFine/COOP) - it has Classes , Inheritance, Exceptions, Unit Testing, and more - with pure C – Shmuel Fine Dec 21 '22 at 21:44

2 Answers2

4

You should definitively have a look at the GTK+ Project Deriving, using events, hierarchies of widgets, through the big amount of code you'll get a good impression on how OO in C can look like. There is even a quite good implementation of Reflexion (which other programming frameworks like Java or .NET have more or less built-in) called "introspection".

Gtk+ is definively a very good example of object oriented programming in C.

jdehaan
  • 19,700
  • 6
  • 57
  • 97
0

One common approach is to design a header file that forward-declares a struct, then defines a number of functions that take a pointer to that struct as a "this" pointer. For example:

struct vector; // Forward-declaration; no implementation shown.

struct vector* VectorNew(/* ... */);
void VectorAppend(struct vector* this, void* toAppend);
size_t VectorSize(const struct vector* this);

Then, in the .c file, you can actually provide the full struct definition and the associated function definitions. This prevents clients from reading the raw fields, since they're only in the .c file, and gives a sort of "namespace" to the "member functions" by using a consistent prefix.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • See the standard library `FILE *` type for this idea in action. Of course, this is only a subset of OO ideas that can be implemented in C. – Chris Lutz Feb 04 '11 at 09:49