Possible Duplicate:
Can you write object oriented code in C?
I'm wondering if it's possible to use strict ANSI C as a object oriented language. And if it's possible, how do I make a class in ANSI C. Allthough the language isn't designed for OO, I'm really eager to try this.
Any examples, links etc. are appreciated.
sort of. remember that C++ and objective-C were both handled at one time with preprocessors to the C compiler. in the end, you'll just be rewriting c++
A struct can hold methods and variables such that
That is how you derive an OO "thing" using a plain old ANSI C compiler, if you want to learn the full OOP with C++ you will fare better with an ANSI C++ compiler as that is a better fit for your needs...as the OOP style using a C language is.... look at it this way, sure you can use a object using a struct, but the name is not exactly...intuitive...as a
struct
is more for holding fields and is part of integral data structures such as linked list, stacks, queues etc. If you had an ANSI C++ Compiler, this is how it would look:Compare and see how it appears more intuitive, information hiding is specified via the
public
andprivate
keywords.It's certainly possible, although I don't like to do it. One of the popular ways of object-oriented C can be found in the GObject architecture used in Gnome. The article (and further reading about GObject) should give you some ideas:
http://en.wikipedia.org/wiki/Gobject
C doesn't have direct support for OO via classes, but you can easily emulate it.
The basics of how to do this is that you can make a struct which holds your data members and an associated list of functions which takes a pointer to that struct as it's first parameter.
More information
There is in fact an effort underway called the OOC language to write a language like C that is object orientated. It is slightly different to C and therefore isn't Objects in C at all, and personally I've never used it - it diverges too far from C for my taste, but it might be worth a look.
It does, interestingly, translate "OOC" to C before compilation. It might be worth a look at how it achieves this as it will effectively be converting objects to C. I suspect this will be done as other posters have mentioned (struct pointers etc) although again I haven't looked at it.