4

Possible Duplicate:
Can you write object oriented code in C?

I am writing a large application in C and have heard that prior to the advent of C++ programmers used to implement the "Object Oriented" pattern in C. My question is what is the usual form this pattern takes? and how would I go about implementing such an OOP pattern in a modern C application?

Community
  • 1
  • 1
horseyguy
  • 29,455
  • 20
  • 103
  • 145
  • 3
    I hate to do this, but have you even searched? http://www.google.com/search?q=object+oriented+c – ryeguy Jul 29 '09 at 16:37
  • 8
    rye there's nothing in the FAQ that says "If an answer can easily be found on google don't ask it here." SO is supposed to be a reference just as much as a question site. – Spencer Ruport Jul 29 '09 at 16:39
  • i did do a search on google prior to asking the Q and i wasn't happy with many of the results. I am also just curious what different patterns there are out there, esp. ones that have been battle tested by veteran programmers and aren't just what some guy thinks might work. – horseyguy Jul 29 '09 at 16:44
  • Hey, links to searches don't work right in comments! I'm off to meta... – dmckee --- ex-moderator kitten Jul 29 '09 at 16:46
  • @Spencer Ruport: But you should avoid needless duplicates of things easily found on StackOverflow, as is the case here. – dmckee --- ex-moderator kitten Jul 29 '09 at 16:52

4 Answers4

10

Here are a few helpful links to guides on Object Oriented C:

jsight
  • 27,819
  • 25
  • 107
  • 140
  • 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:46
4

Where a C++ object has methods, object-style 'C' takes a struct full of function pointers. The functions corresponding to a member function have an explicit data argument that takes the place of the implied 'this' pointer.

Subclasses use function-pointer structs of the same type, with different function pointers to indicate overridded methods.

Steve Gilham
  • 11,237
  • 3
  • 31
  • 37
2

I used to simply adopt naming conventions for a structure and associated "methods". Each method would begin with e.g. CANDIDATE_ for a candidate object, and be associated with a typedef CANDIDATE { ... }, and be in a file Candidate.c

Larry Watanabe
  • 10,126
  • 9
  • 43
  • 46
  • This method always worked for me. Much easier than having a struct of function pointers that needed to all be initialized somewhere. The downside is that you can't do virtual functions without them... – Jerry Jeremiah Mar 16 '21 at 00:59
1

An additional link from someone who wrote several OO frameworks for C.

AProgrammer
  • 51,233
  • 8
  • 91
  • 143