C with Pseudo-Classes

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!
Thank god we use C++ on this C++ website in this C++ forum, or we'd all be doing things the hard way.
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.
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
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.
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
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
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.