← Back to context

Comment by adamrezich

18 hours ago

Namespaces, methods.

Namespaces is not object orientation, is it? Am I missing something? You can place functions (methods) inside of structs in C23, can't you?

  • You can handcode vtables in C, just as you can handcode loops in assembly (i.e. it works but it's verbose, not particularly readable, and brings more footguns).

    But why would you do that if you have an instrument that lets you work at the same level as C, but with methods provided as a proper abstraction that maps exactly to what you'd have written yourself anyway?

    • I don't know, I never found the "proper abstraction" be more than irrelevant syntactic sugar. And the cost of C++ is that you end up putting everything in the header (IMHO the biggest design flaw of the language) and then compile time start to get long....

  • On a high level, "object orientation" means you think of your code as representing the state and interactions of objects. You can equally well do this in assembly. If you think of some namespace as a "singleton object" then that's what it is.

    I guess what you're really asking is what are the best or most common ways to do OO in C?

    • Oh. I learned that object orientation is primarily a way to structure data and code, such that the data is encapsulated with the code that works on it, in so called objects. So an Object is the Data, plus the functions that work on the data, an ensure that some invariants are kept. In OO parlance, that code gets executed by sending messages (calling methods).

      Where can I find something about objects being "think of your code as representing the state and interactions of objects" honesty totally new to me.

      So no, certainly I'm not asking ways to do OO in C. But it seems to be more definitions of object orientation as I thought...

      2 replies →

  • Correct, and you did ask specifically for OO things, but I thought I'd list namespaces too as far as “C++ things you might use when writing C-like C++ code”.

    Another big one that I always forget C still doesn't support is function overloading.

    • Function overloading is a feature that makes code less self-documenting without providing any meaningful value. Operator overloading is more interesting, because you can build you domain language with nice syntax. But I also tend to think that this is not really worth it.

      1 reply →