Skip to content

Instantly share code, notes, and snippets.

@Wollw
Created November 2, 2011 10:51
Show Gist options
  • Save Wollw/1333382 to your computer and use it in GitHub Desktop.
Save Wollw/1333382 to your computer and use it in GitHub Desktop.
A simple (if flawed) implementation of an object in C.
/*
* A simple example of an object in ANSI C.
* It would be better to have initAdder simply call malloc
* and return a pointer to the new object (and be preferable too)
* as this would allow for freeing of objects too but for the sake of
* simplicity I've opted to pass it a pointer instead.
*
* Note that with C++ the "this" variable is pretty much just implicit.
*
*/
#include <stdio.h>
// Declare the "class"
struct adder;
typedef struct adder adder_t;
// Declare the "methods"
void myIncrementer(adder_t *this);
int myGetter(adder_t *this);
// Declare the "interface"
struct adder {
int number;
void (*increment)(adder_t *this);
int (*get)(adder_t *this);
};
/*
* Method to increment an adder's value.
*/
void myIncrementer(adder_t *this) {
this->number++;
};
/*
* Method to get the adder's current value.
*/
int myGetter(adder_t *this) {
return this->number;
}
/*
* Initializer for an adder. Sets the object's methods and
* initializes the value.
*/
void initAdder(adder_t *this) {
this->number = 0;
this->increment = &myIncrementer;
this->get = &myGetter;
}
int main() {
// Create an instance of the object
adder_t myAdder;
initAdder(&myAdder);
// Increment the adder a few times.
myAdder.increment(&myAdder); // number == 1
myAdder.increment(&myAdder); // number == 2
myAdder.increment(&myAdder); // number == 3
myAdder.increment(&myAdder); // number == 4
// Prints "myAdder's value is: 4"
printf("myAdder's value is: %d\n", myAdder.get(&myAdder));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment