I’m working on implementing a dynamic linked list in C just to brush up on my C skills.
Here is the simple struct I use to represent a LinkedList:
typedef struct List
{
Node_t* head;
Node_t* tail;
uint32_t length;
void (*add)(Node_t* head, void* data);
} List_t;
I’m writing this all in its own C file with the hopes that I could include it in some other C file and use the linked list implementation I wrote.
You’ll notice I have a pointer to a function that will add a node to the linked list. (I have several functions other than add, but I just wanted to figure this one out first)
If I were to use this linked list right now, I would have to call it as such
List_t* list = GetList(); /* this is a constructor like method I wrote*/
list->add(list->head, someData);
Is it possible to code it in an OO fashion so that all I would have to do is call:
list->add(someData);
Without passing in the head of the list to the add() function? My instincts tell me that it isn’t possible, but I really like the idea of making my linked lists work that way.
-Akron
Edit: Corrected the reference to add to reflect the fact that list is a pointer
Edit: Looks like the general consensus is no. Thanks for the tips/answers
What you are doing is an OO design.
What you are asking for is syntactic sugar to make your C code look like code in some other language.
I would advise you to stop fighting the language you are using, and instead concentrate on writing good, idiomatic code.
The idiomatic C way for would be to have a function like
And then your client code would just call it like: