Hiding members in a C struct

Marlon picture Marlon · Apr 20, 2010 · Viewed 35.3k times · Source

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 structures. One is defined in the header file and the other is defined in the source file.

// =========================================
// in somestruct.h
typedef struct {
  int _public_member;
} SomeStruct;

// =========================================
// in somestruct.c

#include "somestruct.h"

typedef struct {
  int _public_member;
  int _private_member;
} SomeStructSource;

SomeStruct *SomeStruct_Create()
{
  SomeStructSource *p = (SomeStructSource *)malloc(sizeof(SomeStructSource));
  p->_private_member = 42;
  return (SomeStruct *)p;
}

From here you can just cast one structure to the other. Is this considered bad practice? Or is it done often?

Answer

hobbs picture hobbs · Apr 20, 2010

sizeof(SomeStruct) != sizeof(SomeStructSource). This will cause someone to find you and murder you someday.