C with Pseudo-Classes

Jul 8, 2011 at 9:24pm
http://sites.google.com/site/rcorcs/posts/cwithpseudo-classes

This link shows how to do pseudo-classes in C using structures and function pointers.

It's very interesting and useful.

Using some macro definitions the pseudo-class can be done like in the following example:

1
2
3
4
5
6
7
8
9
CLASS( node,  
   int val; 
    
   FUNC( int, get, (struct node *) ); 
   FUNC( void, set, (struct node *, int) ); 
); 

node *new_node(int v); 
void del_node(node *n);


and it's used as in the following example:

1
2
3
4
5
6
7
8
9
   node *n = new_node(7);

   printf("%d\n", n->get(n));

   n->set(n, 9);

   printf("%d\n", n->get(n)); 

   del_node(n); 


I hope you all like it.

Cheers!
Jul 8, 2011 at 9:38pm
Thank god we use C++ on this C++ website in this C++ forum, or we'd all be doing things the hard way.
Jul 8, 2011 at 9:53pm
Thanks God indeed, and thanks God that I also program in C++, but it's always interesting to learn new C/C++ features... and the more I learn C the more I learn C++ and do good C++ programs.
Jul 8, 2011 at 10:04pm
This reminds me of a time when I resolved to add classes to BBC BASIC. I was 14 so I didn't even get beyond POD but oh well... Now I've left that school, I need never touch the horrible little language again =P

EDIT: That technique actually doesn't look so bad, but of course this:
It is not possible, at least it is not easy, to inherit from another class. What can be done is to create the same functions in the new class that will call the functions of the other one, and it is useful to have an object of the base class as an attribute of the new one.

is a serious problem. Even if there is a work around, you need virtual functions for proper inheritance!

ALL HAIL C++, BLESSED BE HIS HOLY WAYS!
Last edited on Jul 8, 2011 at 10:08pm
Jul 8, 2011 at 10:14pm
Out of historical interest, the first C++ "compiler", CFront, actually worked by turning C++ into (hideous) C code, which was then compiled with a C compiler.
Jul 8, 2011 at 10:31pm
Yeah - I know that all too well from when I used to start C++ books and not get very far, and then start them again a few months later. By the time I'd finished, I'd read the history sections a lot...

When I wanted to try and convert C++ code into BASIC (again, a dead end overambitious project I conceived when I young and naive :o), I even called the program bbcfront =P
Jul 9, 2011 at 2:02am
Out of historical interest, the first C++ "compiler", CFront, actually worked by turning C++ into (hideous) C code, which was then compiled with a C compiler.


Seriously? That's amazing!
Last edited on Jul 9, 2011 at 2:03am
Jul 9, 2011 at 2:12am
closed account (18hDSL3A)
The Comeau C++ compiler still does this. And the Vala compiler (language similar to C#, made specifically for Gnome development), translates to C then compiles with gcc.

It's not that uncommon.
Topic archived. No new replies allowed.