Object Oriented pattern in C? [duplicate] - c

This question already has answers here:
How would one write object-oriented code in C? [closed]
(32 answers)
Closed 1 year ago.
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?

Here are a few helpful links to guides on Object Oriented C:
Object Oriented Programming with C - A very thorough treatment of the subject.
Phil's guide to object-oriented C - This is a rather simplistic approach to the subject, imo.
GObject Reference Manual - GObject is used heavily throughout Gnome and GTK+ applications (mostly on Linux) and therefore provides a thorough example of Object Oriented C in the real world.

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.

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

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

Related

Is Polymorphism possible in C? [duplicate]

This question already has answers here:
How would one write object-oriented code in C? [closed]
(32 answers)
Closed 8 years ago.
Can I include or declare a function inside a structure? I am trying to achieve polymorphism in C. If defining a function isn't the correct way to do it, what other methods can I use?
Polymorphism as a feature of object-oriented languages is not available in C. Neither are encapsulation and inheritance - the language does not have the corresponding features.
This does not mean, however, that it is impossible to model the corresponding behavior with the regular features of C: it is possible to build a library that lets you produce behavior that looks like polymorphism, for example, by using arrays of function pointers.

How is C not object oriented? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can you write object oriented code in C?
Object oriented programming in C
So, as I get it, "objects" are basically just wrappers for values and methods. Can't you have the same functionality in C, with structs? A struct seems just like a simple class, but, of course, it doesn't have any methods. Here we get to the heart of my problem: I don't understand why methods are needed at all. Wouldn't it be simpler and more memory-efficient if we had an outside function, which just accepted a pointer to an instance of a struct? Or even have the structs have pointers to these functions, but this seems purely aesthetic...
Being object-oriented means being object-oriented out of the box. Sure you can simulate object orientation with C (and with many other non-OO languages), but if the language (and/or its standard library) does not help you with that in any way (special syntax, standard objects, etc) and does not encourage to write in OO style by default, it will not be called object-oriented.
Using c-style function pointers as struct members, you can indeed make C object oriented.
I like the concept of having a class with its attributes and methods all defined together. Its easier to see what the related entities are, as opposed to having separate functions that take pointers to the struct like you mention.
Here are 2 related SO questions:
Is there a simple way to code the strategy (or other) design pattern in ANSI C that would fit on the screen of an 11" MacBook Air?
How do function pointers in C work?
What you suggest is already used to implement OO features in C. But many people find easier to use dedicated languages where OO features are included.
This is the same trend as why people switched to C from assembly.
Object is real-world entity and it has state, behavior. In class(c++/java) we can define state as member variables and functions as behavior. In case of C: in struct, you may have state but not behavior. Therefore C is not object oriented. This is just a small e.g. Also C does not support OOPS principals like inheritance, function overloading, polymorphism etc.

Can I use C for Object Oriented Programming? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Can you write object oriented code in C?
Can I use C(not C++!!!) for Object Oriented Programming?
Yes! Object Oriented Programming is A Good Thing, and is very, very possible in C.
Creating objects is not limited to C++ or any other language. Data hiding is easier with C++ and other fourth-generation languages, and having languages that automagically clean up after themselves makes programming easier. BUT! There's always an overhead cost for making the programmer's life easier.
Using pointers to structures is one easy way to implement OOP in C. Linked lists spring to mind immediately. For a (voice)mail system, you could have a mailbox struct that "contained" message structs (as well as the mailbox's own data, of course). Hiding the implementation of a message would be easy; all you'd have to know is that the message had pointers to its mailbox, the previous message, and the next message. Of course, you'd know that a certain set of functions would operate on a mailbox and another set that worked with a message.
The advantage C++ has over C when it comes to OOP is that C++ easily enables you to put methods (actually pointers to them!) into objects. In truth, the methods are just special cases of objects....
There is a book: "Object-Orientated Programming with ANSI-C".
I was always under the impression that you couldn't. This is why: C++ was originally called "C with Objects." There might be a way to, in effect, fake OOP C, but I don't think that it's strictly 100% OOP.
greater minds will be able to clarify this, though
It is a matter of discipline, and you have to build your own framework AND stick to it.
You will have a lot of "syntactical sugar" and you won't have the beauty of expression that a well designed OOP language has. But yes, you can.
Even polymorphism is possible, but you have to write and maintain the appropriate code by yourself.
STRING to_string(OBJECT o)
{
switch get_class(o) {
case CLASS_OBJECT:
return "object";
break;
default:
return "something";
break;
}
}
...

Is the C programming language object-oriented?

I was talking with a co-worker about C and C++ and he claimed that C is object-oriented, but I claimed that it was not. I know that you can do object-oriented-like things in C, but C++ is a true object-oriented language.
What are your thoughts?
Also, it triggered discussion on who decides what it means to be object-oriented and that it's tough to say what object-oriented really officially means. What are you thoughts on this?
If by "is C object oriented?" you mean "is C designed with facilities specifically to support object oriented programming?" then, no, C is clearly not object oriented.
You can program in an object-orientated style in more or less any language. (I think runtime polymorphism -- i.e. virtual methods -- requires a language that supports function pointers.)
Here are a couple of examples:
A short summary of object-orientated style in C: http://www.emilmont.net/doku.php?id=c:object_oriented_c
A comparison between the same program written in C and C++: http://www.eventhelix.com/realtimemantra/basics/object_oriented_programming_in_c.htm
C isn't object oriented. That was the entire purpose behind the ++
As far as a definition of what it takes to be object oriented: check wikipedia.
Personally, if it supports inheritance, encapsulation, and polymorphism then your good to go. Another key here is having nice keywords like class and object tend to help...
Examples of real object oriented languages (not conclusive) are: Smalltalk, Java, c#, Python, Ruby, C++..
Also, it's possible to have extensions to provide OO features like PHP, Perl, VB (not .Net), ...
Real programmers can write object-oriented code in ANY language.
But no, C is not an 'object-oriented' language. It has no concept of classes, objects, polymorphism, inheritance.
Answer can be yes or no, depending on:
if you ask "is C an object oriented language?", the answer is "no" because it do not have object oriented constructors, keywords, semantic etc...
if you intend "can I realize OOP in C?", the answer is yes, because OOP is not only a requirement of a language, but also a way of "thinking", an approach to programming, before to touch some language or another. However the implementation of OOP in C (or any other language not natively designed to be OOP) will be surely "forced" and much hard to manage then any other OOP language, so also some limitation shall be expected.
C is not an O-O language under any definition of "O-O" and "language".
It is quite easy to use C as the implementation language for a component that gives an O-O API to its clients. The X Windows system is essentially a single-inheritance O-O system when viewed from its API, but a whole mess of C when viewing its implementation.
The confusion may be that C can be used to implement object oriented concepts like polymorphism, encapsulation, etc. which may lead your friend to believe that C is object oriented. The problem is that to be considered an object oriented programming language, these features would need to be built into the language. Which they are not.
Unless your friend was talking about Objective C (an OO superset of C) then no, C isn't an OO language. You can implement OO concepts using C (that's what the old cfront C++ compiler did, it translated C++ into C) but that doesn't make C an OO language as it doesn't specifically offer support for standard OO techniques like polymorphism or encapsulation.
Yes, you can write software OO style in C, especially with liberal (ab-)use of macros but as someone who has seen the results of some of those attempts, I'd strongly suggest to use a better suited language.
C is not object oriented in strict sense since it doesn't have a built-in syntax supported object oriented capability like class, inheritance and so on.
But if you know the trick you can easily add object oriented capability to it simply using struct, function pointer, & self-pointer. DirectFB is such a C library written in an object oriented way. The bad thing it is more error prone since it is not governed by syntax and compile type checking. It is based on coding convention instead.
e.g.
IDirectFB/*a typedef of a struct*/ *dfb = NULL;
IDirectFBSurface/*another typedef of a struct*/ *primary = NULL;
DirectFBCreate (&dfb); /*factory method to create a struct (e.g. dfb) with
pointers to function and data. This struct is
like an object/instance of a class in a language with build-in
syntax support for object oriented capability */
dfb->SetCooperativeLevel/*function pointer*/
(dfb/*self pointer to the object dfb*/,
DFSCL_FULLSCREEN);
dsc.flags = DSDESC_CAPS;
dsc.caps = DSCAPS_PRIMARY | DSCAPS_FLIPPING;
dfb->CreateSurface/*function pointer, also a factory method
to create another object/instance */
( dfb/*self pointer to the object dfb*/,
&dsc,
&primary/*another struct work as object of another class created*/ );
primary->GetSize/*function pointer*/
(primary/*self pointer to the object primary*/,
&screen_width,
&screen_height);
2 . C++ is object oriented since it has built-in support for object oriented capability like class and inheritance. But there is argument that it is not a full or pure object oriented language since it does allow C syntax (structural programming syntax) in it. I also remember that C++ lack a few object oriented capabilities but not remember each one exactly.
C is not object oriented language.
C is a general-purpose, imperative language, supporting structured programming.
Because C isn't object oriented therefore C++ came into existence in order to have OOPs feature and OOP is a programming language model organized around objects.
A language in order to have OOPs feature needs to implement certain principles of OOPs.Few of them are Inheritance, Polymorphism, Abstraction , Encapsulation.
C is a object based language, it does not support many features of object oriented languages such as inheritance, polymorphism etc.
Real programmers can write object-oriented code in ANY language.
I have seen Object Oriented Cobol. Cobol that calls Cobol. Do you want to call these programmers "Real"?
C is not Object Oriented.
C does not orient to objects.
C++ does.
Though C itself was bulit as procedural language (it "thinks" in terms of procedure: You first execute function A then you pass the output to function B etc. it supports "out of the box" only functional program flow),
It's possible to implement OOP over C (in OOP, the story is driven by Objects and their responsibilities rather than functions and their calling order).
In fact, some early C++ implementations were translating the code to some C code and then building it.
However, sometimes you must use C (for Embedded devices / GPU languages that don't support C++ etc). And you want OOP. I'd suggest you to check out COOP - my C OOP lightweight yet powerful framework for C object-oriented programming.
C is not object oriented. C++ is not object oriented. Let me explain:
Object Oriented is an extension to Simula's old fashion event driven subset. Real Object Oriented are functional and reflective because Object Oriented is really a group of paradigms (event driven, functional, reflective). Only four language are really object oriented and these are Lisp,Smalltalk,Ruby and Ocaml. Perl lags between because its not functional. Scala is not reflective so also lags behind. C++ is only event driven with some Simula like facilities but its completely structured programming language and its not declarative or even matchs real world. Object Oriented matchs real world with Functional (Maths), Event Driven (Conversations) and Reflectiveness (Evolution). C++ only has conversations. C++ is not declarative like maths or doesnt evolve like life. C++ only converses like people. C++ is like an idiot that doesnt know how maths work or how life evolves.
No, it is not, your friend is wrong.

Does C's FILE have an object-oriented interface?

Does the FILE type used through standard C functions fopen, etc. have an object-oriented interface?
I'm looking for opinions with reasoning rather than an absolute answer, as definitions of OO vary by who you ask. What are the important OO concepts it meets or doesn't meet?
In response to JustJeff's comment below, I am not asking whether C is an OO language, nor whether C (easily or not) allows OO programming. (Isn't that a separate issue?)
Is C an object-oriented language?
Was OOP (object-oriented-programming) anything more than a laboratory concept when C and FILE were created?
Answering these questions will answer your question.
EDIT:
Further thoughts:
Object Oriented specifically means several behaviors, including:
Inheritence: Can you derive new classes from FILE?
Polymorphism: Can you treat derived classes as FILEs?
Encapsulation: Can you put a FILE inside another object?
Methods & Properties: Does a FILE have methods and properties specific to it? (eg.
myFile.Name, myFile.Size, myFile.Delete())
Although there are well known C "tricks" to accomplish something resembling each of these behaviors, this is not built in to FILE, and is not the original intent.
I conclude that FILE is not Object Oriented.
If the FILE type were "object oriented", presumably we could derive from it in some meaningful way. I've never seen a convincing instance of such a derivation.
Lets say I have new hardware abstraction, a bit like a socket, called a wormhole. Can I derive from FILE (or socket) to implement it. Not really - I've probably got to make some changes to tables in the OS kernel. This is not what I call object orientation
But this whole issue comes down to semantics in the end. Some people insist that anything that uses a jump-table is object oriented, and IBM have always claimed that their AS/400 boxes are object-oriented, through & through.
For those of you that want to dip into the pit of madness and stupidity that is the USENET comp.object newsgroup, this topic was discussed quite exhaustively there a few years ago, albeit by mad and stupid people. If you want to trawl those depths, the Google Groups interface is a good place to start.
Academically speaking, certainly the actual files are objects. They have attributes and you can perform actions on them. Doesn't mean FILE is a class, just saying, there are degrees of OO-ness to think about.
The trouble with trying to say that the stdio FILE interface qualifies as OO, however, is that the stdio FILE interface doesn't represent the 'objectness' of the file very well. You could use FILEs under plain old C in an OO way, but of course you forfeit the syntactic clarity afforded by Java or C++.
It should probably further be added that while you can't generate 'inheritance' from FILE, this further disqualifies it as OO, but you could argue that's more a fault of its environment (plain C) than the abstract idea of the file-as-object itself.
In fact .. you could probably make a case for FILE being something like a java interface. In the linux world, you can operate almost any kind of I/O device through the open/close/read/write/ioctl calls; the FILE functions are just covers on top of those; therefore in FILE you have something like an abstract class that defines the basic operations (open/read/etc) on an 'abstact i/o device', leaving it up to the various sorts of derived types to flesh those out with type-specific behavior.
Granted, it's very hard to see the OO in a pile of C code, and very easy to break the abstractions, which is why the actual OO languages are so much more popular these days.
It depends. How do you define an "object-oriented interface"? As the comments to abelenky's post shows, it is easy to construct an argument that FILE is object-oriented. It depends on what you mean by "object-oriented". It doesn't have any member methods. But it does have functions specific to it.
It can not be derived from in the "conventional" sense, but it does seem to be polymorphic. Behind a FILE pointer, the implementation can vary widely. It may be a file, it may be a buffer in memory, it may be a socket or the standard output.
Is it encapsulated? Well, it is essentially implemented as a pointer. There is no access to the implementation details of where the file is located, or even the name of the file, unless you call the proper API functions on it. That sounds encapsulated to me.
The answer is basically whatever you want it to be. If you don't want FILE to be object-oriented, then define "object-oriented" in a way that FILE can't fulfill.
C has the first half of object orientated.
Encapsulation, ie you can have compound types like FILE* or structs but you can't inherit from them which is the second (although less important) half
No. C is not an object-oriented language.
I know that's an "absolute answer," which you didn't want, but I'm afraid it's the only answer. The reasoning is that C is not object-oriented, so no part of it can have an "object-oriented interface".
Clarification:
In my opinion, true object-orientation involves method dispatch through subtype polymorphism. If a language lacks this, it is not object-oriented.
Object-orientation is not a "technique" like GTK. It is a language feature. If the language lacks the feature, it is not object-oriented.
If object-orientation were merely a technique, then nearly every language could be called object-oriented, and the term would cease to have any real meaning.
There are different definitions of oo around. The one I find most useful is the following (inspired by Alan Kay):
objects hold state (ie references to other objects)
objects receive (and process) messages
processing a message may result in
messages beeing sent to the object itself or other objects
a change in the object's state
This means you can program in an object-oriented way in any imperative programming language - even assembler. A purely functional language has no state variables, which makes oo impossible or at least awkward to implement (remember: LISP is not pure!); the same should go for purely declarative languages.
In C, message passing in most often implemented as function calls with a pointer to a struct holding the object's state as first argument, which is the case for the file handling api. Still, C as a language can't be classified as oo as it doesn't have syntactic support for this style of programming.
Also, some other definitions of oo include things like class-based inheritance (so what about prototypal languages?) and encapsulation - which aren't really essential in my opinion - but some of them can be implemented in C with some pointer- and casting magic.

Resources