Inheritance is a powerful mechanism for code organization, unfortunatly the class concept is not present in the C language. Therefore, there is a need for the inheritance mechanism in C where C++ is not available. Inheritance is an extremely complex mechanism, we can only hope to capture a small slice of its features in C without breaking the C language too much. The solution is to make two structures compatible if a pointer to the derived type is upcasted to the base type, therefore we can use the derived type in the base type's procedures.
typedef struct {
float originX, originY;
} Shape;
void SetOrigin(Shape* shape, float x, float y);
float GetOriginX(Shape* shape);
float GetOriginY(Shape* shape);
typedef struct {
Shape base; // this allows Circle* to represent Shape*
float radius;
} Circle;
void SetRadius(Circle* circle);
No comments:
Post a Comment