Related Lists in C: How OO Design Possible?

I'm working on implementing a dynamic linked list in C to refresh my C skills. Here is a simple structure that I use to represent LinkedList:

typedef struct List { Node_t* head; Node_t* tail; uint32_t length; void (*add)(Node_t* head, void* data); } List_t; 

I write all this in my own C file with the hope that I can include it in some other C file and use the linked list implementation I wrote.

You will notice that I have a pointer to a function that will add node to the linked list. (I have several functions besides adding, but I just wanted to parse this first)

If I were to use this linked list now, I would have to call it like this

 List_t* list = GetList(); /* this is a constructor like method I wrote*/ list->add(list->head, someData); 

Is it possible to encode it in OO style, so all I need to do is call:

 list->add(someData); 

Without going to the top of the add () function list? My instincts tell me this is not possible, but I really like the idea of ​​making my linked lists work this way.

-Akron

Edit: Fixed link to add to reflect the fact that the list is a pointer

Edit: It seems the general consensus is not. Thanks for the tips / answers.

+4
source share
2 answers

What you do is OO design.

What you are asking for is syntactic sugar so that your C code looks like code in some other language.

I would advise you to stop fighting the language you use and instead focus on writing good, idiomatic code.

The idiomatic C-method should have a function such as

 void List_Add(List_t *list, void *data); 

And then your client code will simply call it like this:

 List_Add(list, someData); 
+3
source

EDIT : No, I had C ++.

Personally, when I use linked lists, I prefer to have a function like list_add(my_list, node) rather than trying to get my code to look at all OO. You can make things abstract in a way in C, but if I wanted to make my code really OO, I would just use C ++.

+2
source

All Articles