How is C not object oriented? [duplicate] - c

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.

Related

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;
}
}
...

Why use function pointers in a struct in Objective-C?

I just read this Use C Struct in Objective C question, and I was wondering why anyone would want to use function pointers in structs.
Wouldn't wrapping the functions in a class be equivalent?
I don't think that you would need anything like that in objective-c.
That's how you would implement polymorphism in C. It's like defining an interface. Some frameworks (including kernel? filesystem?) would expect you to pass in a structure with your functions which the framework would than call when some event happened.
If you really really need I think you could use c++ and struct/classes from objective-c instead of using plain C structures with function pointers but you should be okay with using objective-c.
Function pointers are used like that in C for creating polymorphic behavior, sort of a poor man's object. The only reasons I can think of doing this other than conforming to an existing C library is to gain a performance advantage over objective-c method dispatch.

Object Oriented pattern in C? [duplicate]

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.

C for an Object-Oriented programmer

Having learned Java and C++, I've learned the OO-way. I want to embark on a fairly ambitious project but I want to do it in C. I know how to break problems down into classes and how to turn them into class hierarchies. I know how to abstract functionality into abstract classes and interfaces. I'm even somewhat proficient at using polymorphism in an effective way.
The problem is that when I'm presented with a problem, I only way I know how to do it is in an Object-Oriented way. I've become too dependent on Object-Oriented design philosophies and methodologies.
I want to learn how to think in a strictly procedural way. How do I do things in a world that lacks classes, interfaces, polymorphism, function overloading, constructors, etc.
How do you represent complex concepts using only non-object-oriented structs? How do you get around a lack of function overloading? What are some tip and tricks for thinking in a procedural way?
The procedural way is to, on one side, have your data structures, and, on the other, your algorithms. Then you take your data structures and pass them to your algorithms. Without encapsulation, it takes a somewhat higher amount of discipline to do this and if you increase the abstraction level to make it easier to do it right, you're doing a considerable part of OO in C.
I think you have a good plan. Doing things the completely OO way in C, while quite possible, is enough of a pain that you would soon drop it anyway. (Don't fight the language.)
If you want a philosophical statement on mapping the OO way to the C way, in part it happens by pushing object creation up one level. A module can still implement its object as a black box, and you can still use reasonable programming style, but basically its too much of a pain to really hide the object, so the caller allocates it and passes it down, rather than the module allocating it and returning it back up. You usually punt on getters and setters, or implement them as macros.
Consider also that all of those abstractions you mentioned are a relatively thin layer on top of ordinary structs, so you aren't really very far away from what you want to do. It just isn't packaged quite as nicely.
The C toolkit consists of functions, function pointers and macros. Function pointers can be used to emulate polymorphism.
You are taking the reverse trip old C programmers did for learning OO.
Even before c++ was a standart OO techniquis were used in C.
They included defining structs with a pointer to srtuct (usually called this...)
Then defining pointer functions in the struct, and during runtime initialize those pointers to the relevant functions.
All those functions received as first paremeter the struct pointer this.
Don't think C in the complete OOP way. If you have to use C, you should learn procedural programming. Doing this would not take more time than learning how to realize all the OOP features in C. Furthermore, basic encapsulation is probably fine, but a lot of other OOP features come with overhead on performance when you mimic them (not when the language is designed to support OOP). The overhead may be huge if you strictly follow the C++ design methodology to represent every small things as objects. Programming languages have specific purposes in design. When you break the boundary, you always have to pay something as the cost.
Don't think you have to shelve your knowledge of object-oriented work - you can "program into the language".
I had to work in C after being primarily experienced in object-oriented work. C allows for some level of object concepts to pull through. At the job, I had to implement a red-black tree in C, for use in a sweep-line algorithm to find the intersection points in a set of segments. Since the algorithm used different comparison functions, I ended up using function pointers to achieve the same effect as lambdas in Scheme or delegates in C#. It worked well, and also allowed the balanced tree to be reusable.
The other feature of the balanced tree was using void pointers to store arbitrary data. Again, void and function pointers in C are a pain (if you don't know their ins and outs), but they can be used to approximate creating a generic data structure.
One final note: use the right tool for the job. If you want to use C simply to master procedural technique, then choose a problem that is well-suited to a procedural approach. I didn't have a choice in the matter (legacy application written in C, and people demand the world and refuse to enter the 21st century), so I had to be creative. C is great for low/medium abstractions from the machine, say if you wanted to write a command-line packet inspection program.
The standard way to do polymorphic behavior in C is to use function pointers. You'll find a lot of C APIs (such as the standard qsort(3) and bsearch(3)) take function pointers as parameters; some non-standard ones such as qsort_r take a function pointer and a context pointer (thunk in this case) which serves no purpose other than to be passed back to the callback function. The context pointer functions exactly like the this pointer in object-oriented languages, when dealing with function objects (e.g. functors).
See also:
Can you write object-oriented code in C?
Object-Orientation in C
Try not to use OOP in C. But if you need to, use structures. For the functions,
take a structure for an argument, like so:
typedef struct{
int age;
char* name;
char* dialog;
} Human;
void make_dialog(Human human){
char* dialog="Hi";
human.dialog=dialog;
}
which works exactly like python's self, or something like that and to access other functions belonging to that class:
void get_dialog(Human human){
make_dialog(human);
printf(human.dialog);
}

What are the pitfalls and gotchas of mixing Objective-C and C?

At the risk of oversimplifying something I'm worried might be ridiculously complex, what should I be aware of when mixing C and Objective-C?
Edit: Just to clarify, I've never worked with C before, and I'm learning Objective-C through Cocoa. Also I'm using the Chipmunk Dynamics engine, which is C.
I'd put it the other way around: you might be risking overcomplicating something that is ridiculously simple :-)
Ok, I'm being a bit glib. As others are pointing out, Objective-C is really just a minimal set of language extensions to C. When you are writing Objective-C code, you are actually writing C. You can even access the internal machinations of the Objective-C runtime support using some handy C functions that are part of the language (no... I don't recommend you actually DO this unless you really know what you're doing).
About the only time I've ever had mildly tricky moments is when I wanted to pass an Objective-C instance method as a callback to a C function. Say, for example, I'm using a pure-C cross platform library that has functions which accept a callback. I might call the function from within an object instance to process some data, and then want that C function to call my instance BACK when its done, or as part of getting additional input etc etc (a common paradigm in C). This can be done with funky function wrapping, and some other creative methods I've seen, and if you ever need to do it googling "objective-c method for c callback" or something like that will give you the goods.
The only other word of advice is to make sure your objects appropriately manage any manually malloced memory that they create for use by C functions. You'll want your objective-c classes to tidy up that memory on dealloc if, indeed, it is finished.
Other than that, dust off any reference on C and have fun!
You can't 'mix' C and Objective-C: Objective-C is a superset of C.
Now, C++ and Objective-C on the other hand...
Objective C is a superset of C, so it shouldn't conflict.
Except that, as pointed here pure C has different conventions (obviously, since there is no built-in mechanism) to handle OO programming. In C, an object is simply a (struct *) with function pointers.

Resources