Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Emulating public and private in C structs

Name: Anonymous 2010-06-15 11:30

Consider:
foo.h:
struct Foo {
        int public_1;
        int public_2;
}
struct Foo * create_Foo ();
void bar_Foo (struct Foo*);
/* etc */

foo.c:
#include "foo.h"
struct Foo_private {
        struct Foo foo; /* ??? */
        int private_1;
        int private_2;
}
struct Foo * create_Foo (void) {
        return malloc (sizeof(Foo_private));
}
void bar_Foo (struct Foo *foo) {
        Foo_private *foo_p = (Foo_private*) foo; /* ??? */
        /* do whatever with foo_p->private_1 and foo_p->private_2 */
}

Is there anything wrong with this? I'm dubious about the lines commented with ???. I don't want to write getters and setters for the 'public' stuff.

Name: Anonymous 2010-06-15 22:52

>>12
Any way is fine, but be careful to only syntax check. If you compile then you have a different struct Foo outside foo.c than inside foo.c, which is a subtle bug waiting to bite.

>>13
If the client abuses the interface then it's his own problem. C simply requires this kind of trust by its design. Trying to idiot-proof your code is an uphill battle against the language. For example, how can you protect against someone passing (void *)0xDEADBEEF to your function?

Name: Anonymous 2010-06-15 22:55

>>13
Private variables protect from accidental access, never from intentional tampering. That would be a terribly dumb thing to try to prevent.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List