I'm fairly new to programming (about four months learning), and have decided to mess about with an attempt at writing a language in C for both fun and practice, and am wondering how objects are implemented when you get down to it.
At the moment I am just looking to turn my 'code' into a c-file, and then compile that, so the approach I am thinking of taking is to make my compiler turn each class-method into a function and the rest of the object a struct, and replace any calls to that method with the function whilst passing the appropriate variables from whichever instance is calling the class-method.(i.e. adding the internals to the list of arguments, and modifying the amount of arguments the method accepts to match)
So my question is (ignoring the other things that objects do at the moment), 'how bad is this approach', and even if it's okay, what is the usual way?
-
The usual way is covered by a number of readily-available resources that discuss compiler design. That way is quite different from the way you've chosen, but that doesn't mean that it's wrong. It sounds to me like a perfectly sensible first approach, from a learning perspective.Robert Harvey– Robert Harvey2016年06月08日 17:52:43 +00:00Commented Jun 8, 2016 at 17:52
-
Thanks. I assume they are quite different because there are advantages then. But if this would work on something simple, I think I'll stick to it now, as I'm really concentrating on C# and also web stuff (taking a course, this is personal project and trying to avoid forgetting what I've learned in C!user232573– user2325732016年06月08日 17:59:28 +00:00Commented Jun 8, 2016 at 17:59
-
5This is a learning exercise. It's only bad if you don't learn anything.Dan Pichelman– Dan Pichelman2016年06月08日 18:00:56 +00:00Commented Jun 8, 2016 at 18:00
2 Answers 2
This sounds like the old CFront compiler - which compiled C++ into C:
Cfront was the original compiler for C++ (then known as "C with Classes") from around 1983, which converted C++ to C; developed by Bjarne Stroustrup. The preprocessor did not understand all of the language and much of the code was written via translations. Cfront had a complete parser, built symbol tables, and built a tree for each class, function, etc.
So your approach has been done before with some success. I would certainly suggest it's a worthwhile technique.
I agree with Robert Harvey... this is not a bad approach. If you would like to see an example of "class" design in c that uses a different approach look at X11/xview/etc https://www.x.org/wiki/guide/ to see how structs are used like classes...
-
Thanks. I'm assuming that there must be advantages to doing it other ways, but am wondering whether those would be in compiling speed, run-time or just advantageous for other things like inheritance etc.user232573– user2325732016年06月08日 18:10:11 +00:00Commented Jun 8, 2016 at 18:10