Can I inherit a structure in C? If yes, how?
If your compiler supports anonymous structs, you can do this:
typedef struct Base
{
// base members
} Base_t;
typedef struct
{
struct Base; //anonymous struct
// derived members
} Derived_t;
This way, base stuct members can be acessed directly, which is nicer.
A slight variation to the answer of anon (and others' similar). For one level deep inheritance one can do the following:
#define BASEFIELDS \
char name[NAMESIZE]; \
char sex
typedef struct {
BASEFIELDS;
} Person;
typedef struct {
BASEFIELDS;
char job[JOBSIZE];
} Employee;
typedef struct {
BASEFIELDS;
Employee *subordinate;
} Manager;
This way the functions accepting pointer to Person, will accept pointer to Employee or Manager (with casting), same as in other answers, but in this case the initialisation will be natural as well:
Employee e = {
.name = "...";
...
};
vs
# as in anon's answer
Employee e = {
.person.name = "...";
...
};
I believe this is how some popular projects do that (eg. libuv)
UPDATE: also there are some good examples of similar (but not the same) concept in libsdl events implementation using structs and unions.
You can simulate it, but you can't really inherit.
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 use pointers to a union
of Base
and Derived
.
No you cannot. C does not support the concept of 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;