Can i inherit structure in C?if yes how?
C is not an object-oriented language and hence has no inheritance.
C has no explicit concept of inheritance, unlike C++. However, you can reuse a structure in another structure:
typedef struct {
char name[NAMESIZE];
char sex;
} Person;
typedef struct {
Person person;
char job[JOBSIZE];
} Employee;
typedef struct {
Person person;
char booktitle[TITLESIZE];
} LiteraryCharacter;
The closest you can get is the fairly common idiom:
typedef struct
{
// base members
} Base;
typedef struct
{
Base base;
// derived members
} Derived;
As Derived starts with a copy of Base, you can do this:
Base *b = (Base *)d;
Where d is an instance of Derived. So they are kind of polymorphic. But having virtual methods is another challenge - to do that, you'd need to have the equivalent of a vtable pointer in Base, containing function pointers to functions that accept Base as their first argument (which you could name this
).
By which point, you may as well use C++!
You can do the above mentioned
typedef struct
{
// base members
} Base;
typedef struct
{
Base base;
// derived members
} Derived;
But if you want to avoid pointer casting, you can using pointers to a union of Base and Derived.