Simplified version how to do object-oriented style objects in C (Polymorphism). (adapted from the book "Understanding and using C pointers")
Because memory for variables in structures are always allocated in the same order they are declared, you can easily define a base-structure for your objects. A base structure for a shape object could be simply coordinates:
Now you can define couple of different shapes that "inherit" from the basic shape-struct. Just remember that the order is important. Always put the base structure at the top.
Now, if you want to have a function that moves a shape to given coordinates, you do not have to write a function for every shape you have. You can write a function that works with the base-structure only.
this is how you would use it:
Because memory for variables in structures are always allocated in the same order they are declared, you can easily define a base-structure for your objects. A base structure for a shape object could be simply coordinates:
C:
struct shape {
int x;
int y;
};
Now you can define couple of different shapes that "inherit" from the basic shape-struct. Just remember that the order is important. Always put the base structure at the top.
C:
struct rectangle {
struct shape base;
int width;
int height;
};
struct circle {
struct shape base;
int radius;
};
Now, if you want to have a function that moves a shape to given coordinates, you do not have to write a function for every shape you have. You can write a function that works with the base-structure only.
C:
// Move the shape to coordinates x, y
void move_shape(struct shape* obj, int x, int y)
{
obj->x = x;
obj->y = y
}
this is how you would use it:
C:
// Declare and init couple of shapes
// A Rectangle
struct rectangle rect;
rect.x=0;
rect.y=5;
rect.width = 10;
rect.height = 3;
// A Circle
struct circle circ;
circ.x = 120;
circ.y = 30;
circ.radius = 5;
// Move the circle to origin
move_shape((struct shape*)&circ, 0, 0);
// Move the rectangle to 10, 12
move_shape((struct shape*)&rect, 10, 12);
Last edited: