Skip to content

Instantly share code, notes, and snippets.

@R2ZER0
Created October 24, 2014 21:58
Show Gist options
  • Save R2ZER0/136e8cc609c90537c049 to your computer and use it in GitHub Desktop.
Save R2ZER0/136e8cc609c90537c049 to your computer and use it in GitHub Desktop.
C encapsulation example
/* Example usage */
#include <stdlib.h>
#include <stdio.h>
#include "foo.h"
void main(void)
{
Foo my_foo = new_foo();
foo_increment(my_foo);
foo_increment(my_foo);
printf("my_foo->count = %d \n", foo_getcount(my_foo));
foo_increment(my_foo);
foo_say(my_foo);
}
/* An actual implementation of foo */
#include "foo.h"
#include <stdlib.h>
#include <stdio.h>
struct foo {
/* Foo's member variables */
int count;
};
/* Constructor implementation */
void foo_init(Foo self)
{
self->count = 0;
}
Foo new_foo()
{
Foo self = (struct foo*) calloc(1, sizeof(struct foo));
foo_init(self);
return self;
}
/* Method implementations */
void foo_increment(Foo self)
{
self->count = self->count + 1;
}
int foo_getcount(Foo self) {
return self->count;
}
void foo_say(Foo self)
{
printf("%s", "I'm a foo! Count = %d \n", foo_getcount(self));
}
/* The "public interface" to class Foo */
struct foo;
typedef struct foo* Foo;
/* Constructor */
void foo_init(Foo self);
Foo new_foo();
/* Some methods */
void foo_increment(Foo self);
int foo_getcount(Foo self);
void foo_say(Foo self);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment