C language: Struct Sub-typing

Tram Ho

When using struct to describe simulated data records about entities, there are certain cases when between entities there is inheritance of properties, obviously we also want to reflect the inherited characteristic. inheritance in code instead of composition combination. inheritance is not syntactically supported by C , but technically by default this feature has been implemented for struct when working through struct pointer .

Structure Pointer

When working with struct through reference pointers, we always have the address of struct which is the address of the first data field in the definition of that struct type.

Backward Casting

This means that if we store the address of a struct_person as the first data field of another struct type, the newly defined struct type can be considered an inheritor of class Person . Because if we have a Worker pointer that inherits from Person in this way, a function defined with an input parameter of Person will also work fine if we pass in the address of the first cell to be stored. Store the type Worker .

 

Share the news now

Source : Viblo