Created
October 24, 2014 21:58
-
-
Save R2ZER0/136e8cc609c90537c049 to your computer and use it in GitHub Desktop.
C encapsulation example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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)); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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