How to inherit the structure in a C plan

advertisements

I am working in a plain C (embedded project, little memory) and I have a structure

typedef struct
{
   int x;
   int y;
   int z;
   float angle;
   float angle1;
   float angle2;
} Kind1;

There are cases when I need all fields, and there are cases when I need x, y and angle only.

In C++ I would create a base class with these 3 fields, would inherit from it another class with additional 3 fields and would instantiate one or another per need. How can I emulate this behaviour in plain C?

I know that I can make something like

typedef struct
{
   int x;
   int y;
   float angle;
} Kind1;

typedef struct
{
   Kind1 basedata;
   int z;
   float angle2;
   float angle3;
}  Kind2;

but then I cannot pass pointer to Kind2 where a pointer to Kind1 is requested.

I know that it is possible to typecast and offset the pointer, I just wonder if there is a better, safer way.


I know that it is possible to typecast and offset the pointer

Not necessarily:

void foo(Kind1*);
struct Kind2
{
   Kind1 basedata;
   int z;
   float angle2;
   float angle3;
}

//...
Kind2 k;
foo(&(k.basedata));