Hiding members in a C struct

前端 未结 14 1998
渐次进展
渐次进展 2020-11-29 21:02

I\'ve been reading about OOP in C but I never liked how you can\'t have private data members like you can in C++. But then it came to my mind that you could create 2 structu

相关标签:
14条回答
  • 2020-11-29 21:42

    Not very private, given that the calling code can cast back to a (SomeStructSource *). Also, what happens when you want to add another public member? You'll have to break binary compatibility.

    EDIT: I missed that it was in a .c file, but there really is nothing stopping a client from copying it out, or possibly even #includeing the .c file directly.

    0 讨论(0)
  • 2020-11-29 21:43

    Personally, I'd more like this:

    typedef struct {
      int _public_member;
      /*I know you wont listen, but don't ever touch this member.*/
      int _private_member;
    } SomeStructSource;
    

    It's C after all, if people want to screw up, they should be allowed to - no need to hide stuff, except:

    If what you need is to keep the ABI/API compatible, there's 2 approaches that's more common from what I've seen.

    • Don't give your clients access to the struct, give them an opaque handle (a void* with a pretty name), provide init/destroy and accessor functions for everything. This makes sure you can change the structure without even recompiling the clients if you're writing a library.

    • provide an opaque handle as part of your struct, which you can allocate however you like. This approach is even used in C++ to provide ABI compatibility.

    e.g

     struct SomeStruct {
      int member;
      void* internals; //allocate this to your private struct
     };
    
    0 讨论(0)
提交回复
热议问题