Should I learn to implement OOP in C? Are there projects that use OOP in C?

前端 未结 6 653
闹比i
闹比i 2020-12-28 17:50

Recently, I finished reading K&R with its, almost all, exercises and examples. I was planning to move to \"Accelerated C++\" that I came across Axel Schreiner\'s book OO

6条回答
  •  半阙折子戏
    2020-12-28 18:30

    OO is used in C as often as needed. Generally I don't agree with the opinion that one cannot do OOP in C, as soon as you provide set of functions that operate on a given type you have OOP. Take for example, you decide to create a data structure. If you provide functions to create, add, remove, and find elements of the data structure it's OO. Generally other languages provide syntactical sugar by automatically implying an instance variable and scoping in various properties of that instance automatically.

    1. As far as "is it really used", the answer is yes. It's not for mental exercise, it's a valid paradigm in C.
    2. The best example that comes to mind is GObject, used by GLib, GTK+ and many projects unrelated to GNOME. GObject provides a way of building objects in C. However it's not necessary to use third party support to have OO in C. Many existing projects have it, although it may not be present in the interface (a great thing in my opinion), and used internally for various purposes (cleanliness, data protection, all the usual OO justifications).
    3. It is a good idea to use OOP in C whenever you find the need to group behaviours and/or data. When you can justify the little extra syntactic expense in using your objects interface, and the time spent not actually completing your solution. Don't get sidetracked.
    4. You should not waste time learning OO because you think it's superior, rather it should complement your future solutions, and you should add it to your toolkit. Use it when it seems the right thing to do. Become familiar with how one does OO in C, the best way would be to do some C++, or examine any good project that uses a little C-style OO. It will seem natural to you after that.

提交回复
热议问题