How to simulate a C++ class in C

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


  • The C version needs to call destroy explicitly, while the C++ version will automatically run deconstructor ~List() to release the memory, or use smart pointers like unique_ptr to help memory management.
    • To release Foo* n = new Foo(...), we need to use delete n instead of n->~Foo()
      • Calling a destructor releases the resources owned by the object, but it does not release the memory allocated to the object itself.
  • We need to pass self pointer to the List structure 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 template instead of void* in the C version.
    • The void* data with size_t size is regarded as memory chunk beyond types, pointed by data with size bytes, so we can store different types data in runtime.
    • While template<typename T> let us to declare a variable with type T in compile time, so gcc/g++ can help us for debugging if there is any error.
      • function with template cannot be separated in .cpp and .h because 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.
  • Replace NULL with nullptr
    • nullptr is always a pointer type. NULL(0) could cause ambiguity when we have functions: void f(int), void f(foo *), and we call f(NULL).