# Coding C in an OO fashion.

## Recommended Posts

I've heard its possible, but I don't know the specifics. You can accomplish data hiding (Encapsulation) fairly easilty by with C, but how would someone go about Polymorphism, and Inheritance, with C. (I'm working a on a new language, that is a cross between Python and C). Thanks for any help, L-

##### Share on other sites
This is generally a bad idea. It's possible, but extremely limited and messy. The GTK GUI toolkit does this, and it's more or less a nightmare. Regardless, GTK is an example (actually, I think that might be part of GLib), and I know I've read an article about this in Dr. Dobbs Journal.

##### Share on other sites
Quote:
 Original post by LucidquietI've heard its possible, but I don't know the specifics. You can accomplish data hiding (Encapsulation) fairly easilty by with C, but how would someone go about Polymorphism, and Inheritance, with C.

Polymorphism can be emulated via function pointers. Your C++ compiler will create a table containing all function pointers, then create a hidden pointer to that table in the data area of each instance.

Inheritance can be emulated by having structures (the derived type) contain members of other structures (the base types). So each base type will be a part of an instance of the derived type.

Emulation of member functions will require name mangling (to avoid conflicts in case multiple classes define a function with the same name) and having each function expect a pointer to its data as additional parameter (this pointer).

##### Share on other sites
Quote:
 Original post by nmiEmulation of member functions will require name mangling (to avoid conflicts in case multiple classes define a function with the same name) and having each function expect a pointer to its data as additional parameter (this pointer).

Thanks, nmi and jonahrowley.

What about structures, for the name mangling problem, I mean if 2 structures have the same function pointers in them, with same names, there shouldn't be conflict I think...

L-

##### Share on other sites
Quote:
Original post by Lucidquiet
Quote:
 Original post by nmiEmulation of member functions will require name mangling (to avoid conflicts in case multiple classes define a function with the same name) and having each function expect a pointer to its data as additional parameter (this pointer).

Thanks, nmi and jonahrowley.

What about structures, for the name mangling problem, I mean if 2 structures have the same function pointers in them, with same names, there shouldn't be conflict I think...

L-

You are right.

On a side note, since "member functions" are implemented as function pointers in C, I don't see why you may need name mangling - just give a diferent name to the new function (C don't allow you to create functiosn with the same name, so it is not really a problem). Did I miss something?

You might also need to play with complex type casting - and in the end, you'll probably end up with something along the line of GLib's GObject, which is pretty heavy.

Regards,

##### Share on other sites
LUA might fit somewhere between C and Python.

But seriously, why do you want to create a new language, and why does that mean you need to know how to use OO facilities in C?

##### Share on other sites
I love to make new languages, its all I ever do when programming. Making interpreters or compilers is bout all I do lol. Im guessing your writing an interpreter/vm for this? If your making a compiler I dont see why you would need to know how to do OO in C...and why dont you just write the interpreter in C++?

##### Share on other sites
What's the goal of your C/Python hybrid?

##### Share on other sites
Quote:
Original post by Lucidquiet
Quote:
 Original post by nmiEmulation of member functions will require name mangling (to avoid conflicts in case multiple classes define a function with the same name) and having each function expect a pointer to its data as additional parameter (this pointer).

What about structures, for the name mangling problem, I mean if 2 structures have the same function pointers in them, with same names, there shouldn't be conflict I think...

You don't have to mangle names to have structures with members of type pointer-to-function. The mangling comes into play if you want to support things like namespaces or overloading.

An excellent example of object-oriented programming using C is the stdio FILE* functions (fopen(), fread(), fwrite(), ftell(), fclose() etc).

Another example is the entire OpenSSL suite, but not for the faint-of-heart.

##### Share on other sites
The first C++ compiler wasn't really a true compiler even, it was some sort of nice preprocessor that converted the C++ code into C code.

So most standard(i.e., not arcane or overly complex) features of C++ are "emulable " in C, in some form or another. Whether it's nice and clean or horribly messy C, that remains a question.

##### Share on other sites
Little off topic but... nice rating Etothex! [smile] lol 1337

##### Share on other sites
One way to simulate polymorphism in C is to create structs with identical fields in identical order and add the extended fields after:

typedef struct{  int a;  int b;} BaseClass;BaseClass *BaseClass_New(int a, int b);void BaseClass_Delete(BaseClass *p);void BaseClass_DoSomething(BaseClass *p);typedef struct{   int a;   int b;   int c;} SubClass;SubClass *SubClass_New(int a, int b, int c);void Subclass_Delete(SubClass *p);// with the above declarations, you can do this:SubClass *sc = SubClass_New(0, 1, 2);BaseClass_DoSomething((BaseClass*)sc);

Any function that takes a BaseClass pointer can take a SubClass pointer as long as it is cast. This technique works well, but can easily become a nightmare to maintain if you make heavy use of it. Imagine if you need to add a new field to BaseClass. Every struct that 'derives' from it will need to be changed. One way to help with this is to keep the 'class' declarations as macros so that they are all in one place:

#define DECLARE_BASECLASS    int a;    int b;#define DECLARE_SUBCLASS    int c;typedef struct{   DECLARE_BASECLASS} BaseClass;typedef struct{   DECLARE_BASECLASS   DECLARE_SUBCLASS} SubClass;

There's a lot you can do to work in an object oriented design in C, but it's best if you don't try to shoehorn things in that just don't fit and make concessions where you need to. In other words, don't get overly zealous. Work within the OO paradigm where you can, but be careful that you don't make your code more complex than it needs to be. C is about simplicity. I've found the best way to use C is to keep things modular and just use OO concepts only where they enhance the design.

##### Share on other sites
First off thanks everyone, you're comments are useful and good.

Quote:
 Original post by RDragon1LUA might fit somewhere between C and Python.But seriously, why do you want to create a new language, and why does that mean you need to know how to use OO facilities in C?

Quote:
 Original post by Falling SkyI love to make new languages, its all I ever do when programming. If your making a compiler I dont see why you would need to know how to do OO in C...and why dont you just write the interpreter in C++?

First run of the approach will be to change everything to working C code, and then see if there are any patterns. Typically one would just write a Grammar, and then generate a Lex/Parser. But the problem is that I think languages that try to take on too much operate under the assumption that just because something is possible in the language makes it suitable for "every" problem with programming. Python does things simply, and elegantly, but its fairly difficult to combat ref counting, or garbage collection, if need be. C is simple as well, but gets bogged down when appealing to greater abstractions.

But you're right I don't think that the end result will be a compiler, but a happy marriage between Python and C.

L-

##### Share on other sites
Quote:
 Original post by smrWhat's the goal of your C/Python hybrid?

Good questions, I've been thinking about how to state this, but here is a little of what I have in mind:

1.) Removal of the dependency of Macros, (and Header files from C, at least from having to be hand written).

2.) Design a Programmable Programming language. (ie Lisp like). But once again without macros. And yes it seems a little odd as to what a Programmable Programming language is, however, its not easy (or very possible) in C/C++ to do something like Obj.GetFunction("blah").doSomething(x,y,z), or Obj.GetAllFunctions() : returns a list, without programming it yourself. That is it's pretty easy to add a member variable that is a list and store pointers to the methods of the class in that list and then return that list, but that's a lot of work when it's something a parser/compiler could do pretty easily.

3.) Add without too much difficulty the ability to plug the language into a data base so as to perform some queries on the attributes of the source. For instance how many objects are dependent on function x, or class y, or variable z. With SQL this would be fairly trivial if the information was already stored properly. The thing is how does one do such a thing with C/C++, easily? (There is little to no freely available grammar ware out there).

4.) Generate Documentation without relying too heavily on seperate tools.

5.) Manipulate the source code programmatically (this is similar to #2 above but should also include the idea of templating/generic programming). Rearranging organizing, and generating builds from within the language. That is the Python portion of the language is more than suitable replacement for Make (with some additional library modules).

I think that covers the big issues,
L-

##### Share on other sites
With OOP in C, you'll have an easier time using delegation ("has a") instead of inheritance and polymorphism ("is a").

Here are a few references.

Object-Oriented Programming With ANSI-C (pdf)
Object Oriented Programming in C
Object Oriented Programming in C
Object-Oriented C Programming

##### Share on other sites
Have a look at the headers for the Athena Widgets (part of the X-Windows distribution on *nix). They provide some insight into implementing inheritance using C.

##### Share on other sites
Quote:
 Original post by LessBreadWith OOP in C, you'll have an easier time using delegation ("has a") instead of inheritance and polymorphism ("is a"). Here are a few references. Object-Oriented Programming With ANSI-C (pdf)Object Oriented Programming in CObject Oriented Programming in CObject-Oriented C Programming

Thanks for that, I think those will be pretty helpful.

L-

PS The second C link is broken, but thanks anyhow.

## Create an account

Register a new account

• ## Partner Spotlight

• ### Forum Statistics

• Total Topics
627681
• Total Posts
2978611

• 13
• 12
• 10
• 12
• 22