Hiding members in a C struct

Posted by Marlon on Stack Overflow See other posts from Stack Overflow or by Marlon
Published on 2010-04-20T01:40:21Z Indexed on 2010/04/20 1:43 UTC
Read the original article Hit count: 312

Filed under:
|
|

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.cpp

#include "somestruct.h"

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

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

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

(I think this is done with a lot of the structures when using the Win32 API, but you guys are the experts let me know!)

© Stack Overflow or respective owner

Related posts about c

    Related posts about struct