Skip to content

Instantly share code, notes, and snippets.

@Wollw
Created November 2, 2011 11:34
Show Gist options
  • Save Wollw/1333430 to your computer and use it in GitHub Desktop.
Save Wollw/1333430 to your computer and use it in GitHub Desktop.
A simple implementation of an object in C using malloc an free for creation and destruction.
/*
* A simple example of an object in ANSI C.
* This example uses malloc to create the new object.
*
* Note that with C++ the "this" variable is pretty much just implicit.
*
*/
#include <stdio.h>
#include <stdlib.h>
// Declare the "class"
struct adder;
typedef struct adder adder_t;
// Declare the "methods"
adder_t *newAdder();
void myIncrementer(adder_t *this);
int myGetter(adder_t *this);
void destroyAdder(adder_t *this);
// Declare the "interface"
struct adder {
int number;
void (*increment)(adder_t *this);
int (*get)(adder_t *this);
void (*destroy)(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;
}
/*
* Constructor for an adder. Sets the object's methods and
* initializes the value.
*/
adder_t *newAdder() {
adder_t *a = (adder_t*)malloc(sizeof(adder_t));
a->number = 0;
a->increment = &myIncrementer;
a->get = &myGetter;
a->destroy = &destroyAdder;
return a;
}
/*
* Destructor for the adder object.
*/
void destroyAdder(adder_t *this) {
free(this);
this = NULL;
}
int main() {
// Create an instance of the object
adder_t *myAdder = newAdder();
// 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));
// Destroy the object
myAdder->destroy(myAdder);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment