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-17 5:56

>>1
Well there doesn't seem to be anything directly wrong with this, as long as people can't do anything useful with a stack-allocated Foo or an array of Foo. A stack-allocation or array-allocation won't have your private data attached to it, so an attempt to access it would be out of bounds.

C99 does provide the necessary exceptions to the strict-aliasing rules to allow you to cast back and forth between Foo and Foo_private. So this is standards compliant, providing it is used correctly.

Honestly you are *much* better off just hiding the whole struct and providing some accessor/mutator functions for the fields you want public. This way your struct cannot be allocated by the developers using it, and it is much better future-proofed; you can safely add extra behaviour to your accessors/mutators later on or completely change the internal implementation and leave these as wrappers. In general you should rarely expose the contents of your structs in C.

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