Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

That you can do functional or OOP in C does not make C either kind of language, it just means that C is flexible enough that you can make the computer do things the way you want it to, no matter what that means, and other languages purposefully prevent you from doing what you might want to do.

C++ is object oriented not because it has compile time support for polymorphism or any of that other bad programming practice, but because classes have code sections that live with them, whether on the stack or in the heap, that can operate only on memory belonging to that instance of the class.

Object oriented programming is a coding style and choice. Some languages make it a first class part of the language design. It is purposefully not part of C.

However you can do OOP like things in C: a popular paradigm is to pass around pointers to structs that (should) live in the heap, and to have a number of functions which work on these structs. This is very similar in practice and mental modelling to OOP as users of C++ might know it, but is distinct in that no code ever lives in the stack or heap, and no code is restricted from operating on any of the program memory.



Hmm. In what sense do you believe that class has a code section that "lives" on the stack or heap?

On a modern system you can't usually do that because of W^X rules (also on a non-x86 modern system the performance would be abysmal if you tried because why waste transistors supporting something only crazy people would want?)

So perhaps notionally in the abstract machine if I have sixteen Clowns in a C++ vector there are sixteen copies of the Clown method squirt_water_at() in the vector too, but I assure you all the compiler emits is one copy of squirt_water_at() for Clowns, to the text segment with the rest of the program code, and maybe if Clowns are virtual, a pointer to a table of such functions lives with each Clown just in case there are Jugglers and LionTamers in the vector too - although compilers can sometimes figure out a rationale for not bothering.


Regardinf W^X, doesn’t the Linux kernel has some optional expensive debug operation that can be turned on/off through a self-modifying code removing the expensive branching?


I mostly agree with you. But "or any of that other bad programming practice"? Polymorphism is not a bad programming practice. Yes, it can be misused. No, that doesn't make it bad in and of itself.


Yep, can definitely do OOP in C. Except over here in embedded land those structs don't live in the heap... but as globals (still referenced via pointers tho).

Was demonstrating the difference between inheritance and composition in OOP C to my junior dev just this week.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: