how to implement a class in c [duplicate]

There are no classes in C, only structs. There are classes in C++.

There is also no private:

struct A
{
   int a, b;
   int c, d;
   int e, f;
};

void func1( struct A* );

void fun( struct A* );

But everything is public.

In order to make things more encapsulated, you would hide the actual implementation detail of struct A and show just a forward declaration with the public methods.

protected makes no real sense as there is no inheritance. You can sort-of implement “friendship” by exposing your detail or its functionality to certain internal modules but friendship is not the same as protected, which simply can’t exist within C.

In your class you have made two of the members public but if we “hide” struct A we hide everything, so provide getters and setters instead.

Alternatively we can “hide” part of our struct, something like:
struct A1;

struct A
{
   struct A1 * privatePart;
   int b, c;  // public part     
};

although it gets “messy” as you have to start allocating the private part (and remember in C there are no smart pointers or destructors so you’ll have to be a lot more careful with memory management).

What a lot of C APIs use for this is a naming convention whereby they call “private” variables “reserved”, often reserved1, reserved2 etc. The compiler won’t stop you writing to them, but you obviously do so at your own risk, and the intention is clear that you are not supposed to access these members (other than direct copying or similar).

Leave a Comment