#include <stdlib.h>
void (*toString)(void);
struct shape {
void (*toString)(void);
int x;
int y;
};
struct rectangle {
struct shape base;
int width;
int height;
};
struct circle {
struct shape base;
int radius;
};
// toString for shape -base structure
void toStringShape(void){
printf("Shape"); // we assume that there is some print-function for us.
}
// toString for rectangle
void toStringRectangle(void){
printf("Rectangle");
}
// toString for circle
void toStringCircle(void){
printf("Circle");
}
// Constructor for rectangle object. It allocates memory for the structure and returns a pointer to it.
struct rectangle* new_rectangle() {
struct rectangle* rect = (struct rectangle*)malloc(sizeof(struct rectangle)); // allocate memory for the structure
rect->base.toString = toStringRectangle; // assign the address of the function "toStringRectangle()" to the "toString" function pointer
rect->base.x = 10;
rect->base.y = 15;
rect->width = 40;
rect->height = 60;
return rect;
};
// Constructor for circle object.
struct circle* new_circle() {
struct circle* circ = (struct circle*)malloc(sizeof(struct circle));
circ->base.toString = toStringCircle;
circ->base.x = 0;
circ->base.y = 0;
circ->radius = 5;
return circ;
}
int main() {
int i;
struct shape* shapes[5];
shapes[0] = new_circle();
shapes[1] = new_rectangle();
shapes[2] = new_rectangle();
shapes[3] = new_circle();
shapes[4] = new_rectangle();
// Now, we can "print" all shapes using a for-loop
for(i=0; i<5; i++) {
shapes[i]->toString();
printf("\n");
}
return 1;
}