Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any workaround for making a structure member somehow 'private' in C?

I am developing a simple library in C, for my own + some friends personal use.

I am currently having a C structure with some members that should be somehow hidden from the rest of the application, as their use is only internal. Modifying by accident one of this members will probably make the library 'go wild'.

Is there any 'workaround' to hide those members so that they can't be accessible ?

like image 854
Andrei Ciobanu Avatar asked Mar 26 '10 10:03

Andrei Ciobanu


People also ask

Can we make structure members Private C?

The answer is "Yes! In C++, we can declare private members in the structure". So the important thing is that "we can declare a structure just like a class with private and public members".

How do I make a struct private?

Yes structures can have private members, you just need to use the access specifier for the same. struct Mystruct { private: m_data; }; Only difference between structure and class are: access specifier defaults to private for class and public for struct.

Are C structs public?

In the C++ language, a struct is identical to a C++ class but has a different default visibility: class members are private by default, whereas struct members are public by default.

Can we define empty structure in C?

It's worth noting that empty structs are only somewhat supported in C and disallowed in C99. Empty structs are supported in C++ but different compilers implement them with varying results (for sizeof and struct offsets), especially once you start throwing inheritance into the mix. Save this answer.


1 Answers

The usual techique is this:

/* foo.h */
typedef struct Foo Foo;

Foo *foo_create(...);

void foo_bark(Foo* foo, double loudness);

/* foo.c */
struct Foo {
  int private_var;
};

You can partially hide data members by defining Foo in the header and FooPrivate in the .c file thus:

struct FooPrivate {
  Foo public_stuff;
  int private_var;
}

But then your implementation has to cast back and forth between Foo and FooPrivate, which I find to be a royal PITA, and is a maintenance burden if you change your mind later and want to make something private. Unless you want suck every last CPU cycle out of the code, just use accessor functions.

like image 103
Marcelo Cantos Avatar answered Oct 17 '22 19:10

Marcelo Cantos