/* * abuse of C syntax to do object programming. * * The cool thing is that this demos subclassing. * * I'm not sure if C syntax actually suports what * I am doing below, but it compiles and runs using * gcc with -Wall and -ansi. I wouldn't be suprised * if this is compiler dependent, and it might also * be broken by things like optimization flags. */ #include #include /* MyClass interface */ typedef struct myClassStruct { int number; void (*printSelf)(struct myClassStruct*); } MyClass; /* MyClass implimentation */ void myClassPrintSelf(MyClass* self) { printf("number: %d\n", self->number); } MyClass* newMyClass() { MyClass* self; self = malloc(sizeof(MyClass)); self->number = 0; self->printSelf = &myClassPrintSelf; return(self); } /* end (MyClass) */ /* SubClass is a subclass of MyClass. * It adds a letter instance variable, and * overrides the printSelf method. */ /* SubClass interface */ typedef struct subClassStruct { int number; void (*printSelf)(struct subClassStruct*); /* extension variables and methods have to appear * below the variables and methods of the parent * class. */ char letter; } SubClass; /* SubClass implimentation */ void subClassPrintSelf(SubClass* self) { printf("number: %d letter: %c\n", self->number, self->letter); } SubClass* newSubClass() { SubClass* self; self = malloc(sizeof(MyClass)); self->number = 5; self->letter = 'a'; self->printSelf = &subClassPrintSelf; return(self); } /* end (SubClass) */ /* function that accepts an object of MyClass, * increments it's number variable, and calls it's * printSelf method. */ void incrimentAndPrint (MyClass* inObject) { inObject->number++; inObject->printSelf(inObject); } /* demo of a sub class being used in a function written for * it's parent class. */ int main(void) { MyClass* object1; SubClass* object2; object1 = newMyClass(); object2 = newSubClass(); incrimentAndPrint(object1); incrimentAndPrint((MyClass*)object2); return(0); }