Saturday, 13 March 2021

Single inheritance in C

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

The difference between class and object.

 The difference between class and object is subtle and misunderstood frequently. It is important to understand the difference in order to wr...