How to simulate a C++ class in C
After learning C++, I am curious about
how could I bring the object-oriented style to C.
Could we simulate a C++ class by struct in C?
To find the answer,
I implement a simple linked list with object-oriented style in plain C.
The key is to use function pointer in struct to
simulate a C++ member function.
you can find my code here
To compare, I also implement a linked list in C++.
Class in C
C++ version
Comparison
- The C version needs to call
destroyexplicitly, while the C++ version will automatically run deconstructor~List()to release the memory, or use smart pointers likeunique_ptrto help memory management.- To release
Foo* n = new Foo(...), we need to usedelete ninstead ofn->~Foo()- Calling a destructor releases the resources owned by the object, but it does not release the memory allocated to the object itself.
- To release
- We need to pass self pointer to the
Liststructure for calling functions to access list’s data, while we don’t need to do that in C++ version because class object can get all data inside itself in its implementation. - To allow storing different data type in the list,
the C++ version use
templateinstead ofvoid*in the C version.- The
void* datawithsize_t sizeis regarded as memory chunk beyond types, pointed bydatawithsizebytes, so we can store different types data in runtime. - While
template<typename T>let us to declare a variable with typeTin compile time, so gcc/g++ can help us for debugging if there is any error.- function with
templatecannot be separated in.cppand.hbecause compiler needs to see both the template definition and the specific types/whatever used to fill in the template. Please read this for more details.
- function with
- The
- Replace
NULLwithnullptrnullptris always a pointer type.NULL(0) could cause ambiguity when we have functions:void f(int),void f(foo *), and we callf(NULL).