Object oriented programming in C (2007)
ldeniau.web.cern.ch
ldeniau.web.cern.ch
Another popular trick is to use opaque structs for private data contained in the public struct in the header. Then, the private code defines the private struct. It’s not perfect information hiding but it separates what is intended public and what is intended to be private.
/* foo.h */
#ifndef FOO_H
#define FOO_H
typedef struct _foo_ctx_t {
int timeout;
void *priv;
} foo_ctx_t;
#ifdef _cplusplus
extern “C” {
#endif
foo_ctx_t *foo_init(foo_ctx_t *self);
int foo_bar(foo_ctx_t *self);
#ifdef _cplusplus
}
#endif
#endif /* FOO_H */
/* foo.c */
#include “foo.h”
#include <stdlib.h>
#define PRIVATE(var) ((foo_private_ctx_t *)(self->priv)->(var))
typedef struct _foo_private_ctx_t {
int whatever;
} foo_private_ctx_t;
foo_ctx_t *
foo_init(foo_ctx_t *self) {
self->timeout = 1000;
self->priv = malloc(sizeof(ctx_private_ctx_t));
if (!self->priv) return NULL;
PRIVATE(whatever) = 0;
return self;
}
int
foo_bar(foo_ctx_t *self) {
PRIVATE(whatever) += self->timeout;
return 1;
}Edit: Is it the new thing to hate on C++? Downvotes aren't arguments
Instead of choosing the OOP system that C++ forces on you; you can just use C and choose which OOP system to use.