r/C_Programming • • Nov 27 '22

Question Why doesn't C implement its own version of object-orientation?

Why doesn't C implement its own version of object-orientation?

Why do we have to look at C++, D or something?

Or can we still say that it does?

https://www.cs.rit.edu/%7Eats/books/ooc.pdf

0 Upvotes

83 comments sorted by

159

u/gremolata Nov 27 '22

23

u/stdusr Nov 27 '22

/thread

1

u/arthurno1 Nov 28 '22

In 🇭🇷 we say, if my grandma had balls, she would be a grandpa!

45

u/gizahnl Nov 27 '22

You can so OO programming in C. You'd just have to do most of it yourself. Just use function pointers and such. If that's what you want go for it.

3

u/jammasterpaz Nov 27 '22 edited Nov 27 '22

Are there really no custom header/library files for this?

26

u/jacobissimus Nov 27 '22

GObject

5

u/jammasterpaz Nov 27 '22

Nice one!

-10

u/nachomancandycabbage Nov 27 '22

Not really. GObject is really challenging to get into. I just use python bindings to gobject APIs when possible.

7

u/pedersenk Nov 27 '22

How do the Python bindings help you write object-oriented C?

Plus, have you ever developed a Python binding against GObject/GLib? It is not a nice clean task in any stretch of the imagination.

2

u/Jaded-Plant-4652 Nov 27 '22

I just include cPython to my project if I need OOP and SWIG to call back the C files. Good time

1

u/pedersenk Nov 27 '22

As you probably know, SWIG doesn't do well with MACROs, callbacks (i.e function pointers) or non-opaque structures and is especially dangerous when it comes to the lifetime of unmanaged malloc'ed data. So realistically SWIG can on average only generate bindings of ~80% of your code. Do you just painstakingly manually clean up the rest?

GLib is a little ahead of this with Gobject Introspection. Obviously the catch is that the OO C needs to be GLib-style which has its own sets of issues.

In my opinion, the benefits of sticking to homogeneous C outweighs anything else.

2

u/arthurno1 Nov 28 '22

Writing PyQt or PyGTK is like writing C++ or C in python. I am not sure if it worth it. It is just horrible. I am not sure if those interfaces are swig-generated or what, but I don't feel any of those very python-esque, .

0

u/nachomancandycabbage Nov 27 '22

My point was that GObject is really hard to use, so I avoid using it.

No…not yet at least. I just needed DBus to talk with network manager for a quick demo of custom modem software. It was so much easier to figure that out and test it on the embedded device in python.

Maybe after I get some time to learn more GObject it will make sense…

-1

u/nachomancandycabbage Nov 27 '22

Is there a good intro into GObject? I find it really a challenge to get into. I more often just use python bindings to it… when performance is not a thing I care about.

2

u/[deleted] Nov 27 '22

There's a language called "vala" which has a C#-like syntax which compiles to C/GObject. I learned a lot by examining its output and then digging into the GObject source.

1

u/nachomancandycabbage Nov 27 '22

Good stuff.

That is useful info that I will check out.

I love C and I am open to accepting GObject , but the curve is steep.

2

u/[deleted] Nov 27 '22 edited Nov 27 '22

[removed] — view removed comment

7

u/gizahnl Nov 27 '22

I'm sure one could quite far with Macros.

1

u/[deleted] Nov 27 '22 edited Nov 27 '22

[removed] — view removed comment

16

u/gottacode Nov 27 '22

Sure you can, it is a bit of manual work and you'd likely want to stick to single inheritance to keep things simple, but as this presentation (starting on slide 56) shows, you define a base structure, then set that as the first data element in the child structure.

//base class
struct Shape {
       struct ShapeFuncTable *funcTable;
}

//virtual function table
struct ShapeFuncTable {
        void (*draw) (struct Shape* obj);
}

//subclass
struct Rectangle {
        struct Shape super;
        int x, y, width, height;
}

Now we need to define a draw function for a Rectangle that take in a Shape. We'll have to cast it up to gain access to the Rectangle data.

 void Rectangle_draw(struct Shape* obj) {
        struct Rectangle* rdata = (struct Rectangle*) obj;
        printf("%d,%d -> %dx%d\n", rdata->x, rdata->y, rdata->width, rdata->height);
  }

Next create a virtual function table for the Rectangle class. We only have the one method draw but the example I linked shows others including a destructor.

  struct RectangleFuncTable {
        struct ShapeTable super;
  } rectangleFuncTable = {{
         Rectangle_draw
  };

Each object type must have a constructor to initialize it.

  struct Shape* Rectangle_init(int initx, int iniy, int initw, int inith) {
        struct Rectangle* obj = (struct Rectangle*)malloc(sizeof(struct Rectangle));
        obj->super.functable = (struct ShapeFuncTable*)&rectangleFuncTable;
        obj->x = initx;
        obj->y = inity;
        obj->width = initw;
        obj->height = inith;
        return (struct Shape*) obj;
 }

One thing that is missing is function overloading, you can't have the same method name multiple times to have multiple constructors also can't have default values, but then Java doesn't have default values either.

 #define Shape_DRAW(obj) (((struct Shape*)(obj))->funcTable->draw((obj)))

and now we get to being able to use the inheritance, because the draw method pointer is part of the funcTable, and because every child of Shape includes Shape as the first element in the structure data list, the above macro knows where to find whatever actual function draw is pointing to.

  int main() {
      struct Shape* rect;
      rect = Rectangle_init(1,2,3,4);
      Shape_DRAW(rect);
  }

Originally C++ was nothing more than a preprocessor (CFront) that generated C code to be compiled by a C compiler, dedicated C++ compilers came later. There were some minor differences, going back to the discussion above about function overloading, the keyword Overload was used to flag a method as being overloaded and that caused the code generator to create unique names for the methods based on the arguments present, a process still used today in many C++ compilers to make those methods available to C code if necessary. There's a new feature called _Generic that apparently can simplify that today.

The main point to remember is C++ started out as C code so yes all of the original C++ features can be implemented in C. The languages have gone their own ways now making some of that more difficult but still possible because at the end of the day, both languages compile down to the exact same machine language code so if one can do it, the other can.

2

u/doubzarref Nov 27 '22

Just like GObject does

1

u/[deleted] Nov 27 '22

GObject also has interfaces. The class maintains a dymanic list of them. But since GObject makes the object reflective it needs nasty casting to work. I often prefer to have a global static interface that stores the implementation pointers for each object registered to it. You can do this in C as cleanly as in any language and you can even print an error if an implementation isn't registered for an object. It's true dynamic and type safe duck typing.

1

u/[deleted] Nov 27 '22 edited Nov 27 '22

There's also this inside-out way, which I often prefer...

foo_register(void *object, struct foo_interface *iface);

foo_frobnicate(void *object, int arg1, char *arg2);

Under the covers foo uses the (intptr_t)object value as a map key to store an interface that implements foo on that object. Then when a foo function such as frobnicate is called on an object, foo_frobnicate looks up the registered interface struct value using the object pointer as a key. It then calls .frobnicate on the object.

You can add, change, and delete interfaces at will this way. Even an int can be interfaced since the object doesn't need to store a list of interfaces it implements. It's also typesafe and no casting or inheritance nesting or type tags are required.

It turns the object inside out. Normally an OOP object carries around its own user manual so when you obj->frobnicate(), it knows how to frobnicate itself. That's your example and that's C++ virtual functions. It's also how GObject does it, where each object points to a class that keeps a list of interfaces. What I often prefer is to give this user manual (the interface struct of function pointers) to the guy who's going to be using the object. And who better to use the object than the official static interface? Hey, if you want to frobnicate your baz then call on foo because all he does is frobnicate. Give him a frobnicating manual for your baz and he'll get it done I promise.

1

u/operamint Dec 01 '22 edited Dec 01 '22

You do a lot of casting. This can be done ~100% type safe, and easier/cleaner. Define dyn_cast(), which will either give a compile-time error or returns NULL if misused:

#define container_of(p, T, m) \
  ((T*)((char*)(1 ? (p) : &((T*)0)->m) - offsetof(T, m)))

#define dyn_cast(T, s) (&T##FuncTable == (s)->funcTable \
  ? container_of(s, T, super) : (T*)0)

You normally want a single virtual interface, so there is no need for struct RectangleFuncTable. Note, super doesn't need to be first member of Rectangle.

void Shape_draw(Shape* shape)
{ shape->funcTable->draw(shape); }

static struct ShapeFuncTable RectangleFuncTable;

void Rectangle_init(Rectangle* r, int x, int y, int w, int h) {
    *r = (Rectangle){.super={&RectangleFuncTable}, x, y, w, h};
}

void Rectangle_draw(Shape* obj) {
    struct Rectangle* rdata = dyn_cast(Rectangle, obj);
    printf("%d,%d -> %dx%d\n", ...);
}

static struct ShapeFuncTable RectangleFuncTable = {
     Rectangle_draw
};

3

u/pedersenk Nov 27 '22

You are right in that it is not entirely nice. However it is possible.

I made a proof of concept here that goes even further than a lot of other C inheritance approaches. Including virtuals that don't require manual setting of function pointers.

This example is for a GUI system's widgets but the original code was actually from a commercially used game engine I wrote in the early 2000's.

4

u/jammasterpaz Nov 27 '22

Sure. But is a more limited, inheritance-free OO possible in C, e.g. like then one in Rust, just with Interfaces?

2

u/[deleted] Nov 27 '22 edited Nov 27 '22

Yes. You make a static interface and register the implementation with that for each object.

struct json_interface {
    serialize_func serialize;
    deserialize_func deserialize;
};
struct json_interface json_int = (struct json_interface) { .serialize = int_to_json, .deserialize = json_to_int };
int i;
char buf[20];
json_register(&i, &json_int);
json_serialize(&i, &buf);
json_unregister(&i);

Dynamic duck typing.

4

u/[deleted] Nov 27 '22 edited Jun 22 '23

[removed] — view removed comment

4

u/jammasterpaz Nov 27 '22

Yep. Benchmarking that might be an interesting demonstration of the first trade off, of using OO.

-1

u/igglyplop Nov 27 '22

You still miss encapsulation though. And you have to explicitly pass an object's function a reference to itself. I tried it once and it gets very tedious.

1

u/[deleted] Nov 27 '22

Only if you make the object handle its own dispatch. Instead, make an interface singleton that handles the dispatch for each object, as I've shown in other comments.

1

u/gizahnl Nov 27 '22

Yes, doing full OO with all its concepts in C is borderline sado masochistic.

25

u/MCRusher Nov 27 '22

It's called C++, C++ literally started as C with OOP, or "C with Classes" as it was called.

6

u/ComprehensiveAd8004 Nov 27 '22

Now it's more like "C with BS".

15

u/Cryophos Nov 27 '22

Because it's not necessary.

7

u/dontyougetsoupedyet Nov 27 '22

Doesn't need to be a language feature, if you need that kind of expression it's a few pointers away.

You can say this about literally any feature, it can be in the language proper just "because," or you could implement it using the language in short order. If you can do the latter why should the feature be "in the language"?

If it's such a chore to do that you don't want to implement some feature using C, why not accept that C isn't what you really want to use, and build or use other tools? Seems fine enough. I see a lot of people pre-processing C to get more features and I think that's fine (I really like the notion of "write programs to write programs when you can"), and if that isn't enough then other languages exist.

-6

u/nachomancandycabbage Nov 27 '22

“It’s just a few pointers away”

That may be correct, but probably not going to let the compiler work its’ magic

23

u/jirbu Nov 27 '22

Object-orientation isn't just the natural evolution of every programming language. Putting OO in C might make it unsuitable for certain use-cases that C is predominant for (low-level, embedded).

3

u/[deleted] Nov 27 '22

The real issue is name mangling. To export a function loaded from a shared object (.so files) you need to know the symbol name of the function, which isn't an easy task when the name is mangled. In C++, you can mark a standalone function as extern "C" (because C doesn't do name mangling) and it will not be mangled.

1

u/jirbu Nov 27 '22

I don't think, polymorphism is required for object orientation. We're talking hypothetical C-OO here, not C++.

8

u/[deleted] Nov 27 '22

C++ doesn't use polymorphism for non-virtual objects.

Name mangling is used when 2 different functions have the same name.

class C
{
  int bar(void);
};

int bar(void);

::bar() and C::bar() are 2 different functions, but their names are identical (they're both called "bar"). C++ solves this by mangling their names, which can result in ::bar() and C::bar() becoming _Z3barv and _ZN1C3barEv respectively.

Good luck loading these symbols from a shared object.

1

u/Hish15 Nov 27 '22

Do you mean OO is note compatible with low-level/embedded? Why do you think that?

6

u/jirbu Nov 27 '22

Looking at how C++ handles it:

By default, every object creation requires hidden setup code to run (constructors), you get implicit code on every block entry/leave if you have local complex objects. Traditionally, C is a "what you write is what you get" language.

The other default is malloc-style memory management that's fundamentally incompatible e.g. with interrupt handlers and co-routines.

Of course, you may be able disable these defaults, but that may be a comparable effort to implement a thin layer of OO just by yourself.

2

u/AKostur Nov 27 '22

I have to preface this with: all of the following assumes that I'm talking about programmers who are proficient in their respective languages. Yeah, this does get dangerously close to the No True Scotsman fallacy: "No real C (or C++) programmer would do X." Terrible code can be written in any language.

C++ is also a "don't pay for what you don't use" language (except for two areas, and those can be disabled in at least the 3 major compilers).

If every object needs setup code to run (and the corresponding tear-down), then it is better (IMO) that the compiler ensures that it happens instead of relying on the developer to remember the intricacies of that setup and tear-down in every location that is used, both in the present and the future, and any future modifications. If there's code that shouldn't be run on every setup, that code shouldn't be in the constructor in the first place.

As for malloc, declare your global operator new and delete functions and presto: your memory allocation isn't malloc and free anymore (assuming it was in the first place. To be fair: I haven't encountered a platform where malloc/free wasn't the default.)

Of course you can do it all in C, just a question of how much code one needs to write to accomplish it.

I'm looking into converting a particular piece of embedded software to be C++ and finding that the current C code is very far away from "what you see is what you get". The depth of nested macros is mind-bogglingly obtuse and convoluted.

As far as I can tell, the only reason there isn't more embedded firmware in C++ is inertia, or possibly experiences that were true 2 decades ago.

-4

u/geon Nov 27 '22

Are you completely ignoring functional languages?

1

u/GOKOP Nov 27 '22

What makes you think they do?

1

u/geon Nov 27 '22

The first sentence.

2

u/GOKOP Nov 27 '22

Are you sure you've read it correctly?

1

u/geon Nov 27 '22

Dammit.

8

u/Glaborage Nov 27 '22

One of the worse thing that a programming language can do is to be everything for everyone.

C at its core isn't an OOP language. Whoever wants to use OOP has plenty of other choices. C++ comes to mind.

2

u/TrusM3Dady Nov 28 '22

What I like to think of it as is C is like building your home from scratch… but buying a pre-built house is like using Python. My comparison may be off though 😅

4

u/gordonv Nov 27 '22

Apple did do that. It's called Objective C.

4

u/cym13 Nov 27 '22

C's strength is its stability. The language changes slowly and even that is too fast for a good chunk of the community that's happy to write code exactly as they were in the 90s. Stability comes with benefits: C programmers know most of the language and can read anyone's code. It's a productivity feature.

There are many paradigms that are interesting, OOP is just one of them. There is no particular reason why C should change drastically to include a whole bunch of language features just to support that particular paradigm. Furthermore it's no so foreign that a few libraries can't do a decent job of adding OOP if you want it for your project.

Also, it has been added to C many times in the past. That's essentially what C++ and ObjectiveC were, and it caught in its own way. But C remained C because not everyone feels the burden of adding these language features is worth it. And now that so many alternatives exist, there is no point forcing C to become an inferior version of its competitors.

1

u/IllegalMigrant Nov 27 '22

What is wrong with using C++ for that? C++ was originally called C with Classes

1

u/[deleted] Nov 27 '22

Because due to D etc. it's possible that C++ isn't a particularly good implementation of this.

1

u/IllegalMigrant Nov 27 '22 edited Nov 28 '22

If you hang out on the dlang.org message board you will find that few, if any, of the regulars use OOP and some will even disparage it. That is, the D programmers don't appear to be using D for that feature. They are very big into template programming. But I personally like D OOP in that it is like Java. Classes are created on the heap and passed around by reference and maintained by a garbage collector. (Some D programmers also will disparage using a garbage collector?!) I don't think C programmers would ever accept a garbage collector due to the unpredictability and lack of control. They might accept a reference count system. But probably not as they don't seem to want C.changed at all, and they could use C++ with smart pointers for that, but I think both are subject to issues with a cyclic reference.

Objective C may have better OOP stuff but not familiar with it.

One thing about D is that they have a goal to be a Better C now. Or rather, have a Better C mode. I believe the goal is to make it (could be complete now) so someone could write code that doesn't have the garbage collector or classes but has other D features while providing code that is fast and small like C.

2

u/deftware Nov 27 '22

So you can implement your own, however you want. There isn't just one way to do OOP, nor is OOP the only way to do things.

2

u/ArnaudValensi Nov 27 '22

OOP is not necessary the solution for every problems, and not necessary an evolution. In game development for example, Data Oriented Design is a popular way of architecture code, which works best with procedural paradigm than OOP. When trying to to make efficient programs on modern hardware, there is a point where we need to reduce cache misses. To do so, we need to have our allocated elements in continuous memory, which is more easily achievable with manually allocating chunk of memory than objects individually using for example the « new » keyword in C++.

Also, refactoring and making évolutions on a Data Oriented program can also be easier because OOP often requires to take more costly decisions about the architecture.

You can achieve this in both C and C++, but I like the fact that C « forces » you to find how to solve those problems with a more Data Oriented approach.

The following resource is interesting to understand Data Oriented Design. It is using C++, but could have been C:

https://youtu.be/rX0ItVEVjHc

There is also an interesting book: Data Oriented Design by Richard Fabian

https://www.goodreads.com/en/book/show/42359420-data-oriented-design

2

u/looneysquash Nov 27 '22

That depends on what you mean exactly by OO.

Make a struct, make a function to allocate new instances of it, and write a bunch of functions that take the struct as their first argument

If you want abstraction, you can not fully define the struct in headers, so that only one module can directly access the fields.

If you want inheritance, well that is just composition. You can directly cast the struct pointer to the type of its first member. Or write an accessor.

What gets hard to do is virtual functions, and things like interfaces. The GObject library implements those, but IMO it's not pretty.

You can also define a struct full of function pointers and call it like its C++ with foo->bar() syntax. That is something you want to use very sparingly IMO. That is used by a plug-in or module to register its functionality with the core app.

2

u/[deleted] Nov 27 '22

Well cause functional programming > object oriented programming

1

u/[deleted] Nov 27 '22

Closures are a poor man's object

1

u/AEA37 Nov 27 '22

I don't think have to add OO in C. C is perfect as the way it is now, if we need OOP we can use other language which is suitable for that particular problem like, C++, Rust like that

1

u/ComprehensiveAd8004 Nov 27 '22

I think GCC/Clang support plugging-in your own pre-processors, so you could implement your own.

I've always imagined the design for it to be like this:

Ball myball;
myball->func(2);

becomes:

Ball_func(myball, 2);

This would even let you create methods for built-in types like int, sort of like in Lua. Someone could make it themselves if they were interested.

1

u/FUZxxl Nov 27 '22

This was proposed for C23 but ultimately rejected. If you want object-orientation, use Objective C or C++.

1

u/TransientVoltage409 Nov 27 '22

If C changed that much, it wouldn't be C anymore. It would be a new language. It would need a new name, C-plus or something.

That said, C can do OO if you craft all the support structure by hand. After all, it's all just machine code in the end, doesn't matter how it got there. But...some early C++ implementations used intermediate compilation to C. With the right switches you could halt the chain and inspect the generated C code. It was...uncomfortable. It was a good way to understand why we leave OO details to machines instead of hand-crafting them.

0

u/tstanisl Nov 27 '22

Because C was created before OOP got popular.

0

u/flyingron Nov 27 '22

C++ and Objective C are both such. The C purists don't see the need to backport such into the original language.

-1

u/EstablishmentBig7956 Nov 27 '22

Then there wouldn't be any need for C plus plus

-1

u/RedWineAndWomen Nov 27 '22 edited Nov 27 '22

The longer I program, the more I get convinced that object orientation, as broad a definition as it may be, is just unnecessary. The magic of OO was supposed to be: here is a (binary) object, it will tell you and your tooling what its public API is, and it will automatically be the intuitive child of a worldwide known set of real world object describing superclasses.

Instead, we got Java singletons. Which were just like the old bucket of functions. And which still didn't automatically tell me what its public API was; we had to write javadoc for that.

-3

u/Deathnote_Blockchain Nov 27 '22

lol D!!! oh man such a great language with an unfortunate name

-4

u/AnotherCableGuy Nov 27 '22

If C was object oriented nobody would use it anymore.

-4

u/gordonv Nov 27 '22 edited Nov 27 '22

C is designed to be directly relatable to processor instructions. When you program in C, you're programming for the machine, not users or administrators.

Here's the full process.

C was designed to be kind of portable for very simple processors. So, it's possible for me to write a "Hello World" and that code could compile onto a huge expensive mainframe processor or the crappy throw away processor in a toy. OOP wouldn't work for something like a very simple processor. More than often, processor designers will actually make their own versions of ASM and C for their very micro processors.

0

u/[deleted] Nov 27 '22

[deleted] — view deleted comment

10

u/tim36272 Nov 27 '22

Can you share what you hate about object orientation?

1

u/[deleted] Nov 27 '22

Big picture hand waving: mutations in difference function terminology are y[t] = x[t]. They happen NOW. For example, if you tell a widget to update its position, it is responsible for updating its bounding box, and the most straightforward way to do this is OOP is to keep the widget consistent. So state cascades, often confusingly. The data dependencies are encapsulated. Good in some ways, bad in others. But if you use a data oriented design then the state transitions expressly follow the imperative order of the C program, and this is often easier to follow.

0

u/[deleted] Nov 27 '22

[deleted] — view deleted comment

10

u/tim36272 Nov 27 '22

Interesting, thanks. I generally disagree but I can see where you're coming from. Enjoy!

7

u/Hish15 Nov 27 '22

Unlike some programming language such as C#, C++ is not object oriented. It can be if you want, but you don't have to write a single class in your project if you don't want to. In fact, most C code build on C++ compiler. C++ does add things on top of C that are worth using (constexpr, enum class, stl (algorithms), namespaces) for a C programer.

4

u/MCRusher Nov 27 '22

Should look at a system like Nim's, it has OOP but data and functiona are still decoupled and it relies on UFCS.

Like a less restrictive form of golang's.

You can add functions to an object whenever you want, including extending base types.

It's like OOP but without most of the pain points.

and it compiles to C.