Skip to content

Instantly share code, notes, and snippets.

@nmmmnu
Last active August 29, 2015 13:57
Show Gist options
  • Save nmmmnu/9724218 to your computer and use it in GitHub Desktop.
Save nmmmnu/9724218 to your computer and use it in GitHub Desktop.
OOP using plane C
#include <stdlib.h>
#include <stdio.h>
/*
* Base class. It defines int area() method.
* The class is abstract so we did not made constructor.
* Calling the area() method will probably core dump.
*/
typedef struct{
char *_classname;
int (*area)(void *);
} Figure;
/*
* Circle class. It "extends" Figure class.
* _newCircle() is the constructor.
* it allocates the memory, initialize the fields and maps the area() method.
*/
typedef struct{
char *_classname;
int (*area)(void *);
int radius;
float (*areaFl)(void *);
} Circle;
float CircleAreaFL(Circle *self){
return 3.14 * self->radius * self->radius;
}
int CircleArea(Circle *self){
return (int) CircleAreaFL(self);
}
Circle *_newCircle(int radius){
Circle *circ = malloc(sizeof(*circ));
circ->_classname = "Circle";
circ->radius = radius;
circ->area = (int(*)(void *)) CircleArea;
circ->areaFl = (float(*)(void *)) CircleAreaFL;
return circ;
}
/*
* Rectangle class. It "extends" Figure class.
* _newRectangle() is the constructor.
* it allocates the memory, initialize the fields and maps the area() method.
*/
typedef struct{
char *_classname;
int (*area)(void *);
int a;
int b;
} Rectangle;
int RectangleArea(Rectangle *self){
return self->a * self->b;
}
Rectangle *_newRectangle(int a, int b){
Rectangle *rect = malloc(sizeof(*rect));
rect->_classname = "Rectangle";
rect->a = a;
rect->b = b;
rect->area = (int(*)(void *)) RectangleArea;
return rect;
}
/*
* Square class. It "extends" Rectangle class.
* _newSquaree() is the constructor.
* it uses parent constructor for instanciate the class.
*/
typedef struct{
char *_classname;
int (*area)(void *);
int a;
int b;
} Square;
Square *_newSquare(int a){
Square *sq = (Square *) _newRectangle(a, a);
sq->_classname = "Square";
return sq;
}
/*
* print_area() knows to work only with the base Figure class.
*/
void print_area(Figure *f){
printf("%-30s %d\n", f->_classname, f->area(f));
}
/*
* main() function
*/
int main(){
/* Create 10 x 15 rectangle */
Rectangle *rect = _newRectangle(10, 15);
/* Create 10 x 10 square */
Square *sq = _newSquare(10);
/* Create 5R circle */
Circle *circ = _newCircle(5);
/* print the area */
print_area((Figure *) rect);
print_area((Figure *) sq);
print_area((Figure *) circ);
printf("Circle->areaFl = %.4f\n", circ->areaFl(circ));
/*
* free the resources,
* note did is not the same as destructor.
* destructor must be implemented in a way similar to the constructor.
*/
free(rect);
free(sq);
free(circ);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment