Inheritance in C would need a simple compiler hack
How I usually do it
I used to and often still do inheritance like schemes in C like this
#define X_BASE \
char *name
struct x
{
X_BASE;
};
// y inherits from x
#define Y_BASE \
X_BASE; \
int info
struct y
{
Y_BASE;
};
and so on. This means that the member layout of struct x and struct y is identical for the common members. Therefore you can use a function operating on struct x also on struct y (with casting).
e.g.
static inline char *x_get_name( struct x *p)
{
return( p->name);
}
static inline char *y_get_name( struct y *p)
{
return( x_get_name((struct x *) p));
}
As you can imagine, this necessitates a lot of casting, when using struct x functions from struct y code.
An alternative way
struct x
{
char *name;
};
struct y
{
struct x base;
int info;
};
It’s hopefully obvious that here
struct y a_y;
assert( (void *) &a_y == (void *) &a_y.base);
the only difference between &a_y
and &a_y.base
is the pointer type. The pointer value is the same. Now I know this and the compiler knows this too.
So imagine the compiler wouldn’t complain on pointer type if the struct doesn’t match but the first member does. This would make this kind of inheritance convenient, because I wouldn’t have to cast so much.
In the example above, one would not need or want to code
y_get_name
It’s not technically wrong, the pointer does match. In this sense the pointer to a struct y
has really a dual type, it matches struct y *
and struct x *
.
Furthermore struct y *
will eventually also match char **
, because char *
is the first member of struct x
. This is also not wrong but intended.
After all this is C and not C++, right ?
Avoiding the char ** match
struct root
{
};
struct x
{
struct root root;
char *name;
};
struct y
{
struct x base;
char *info;
};
Continue to C Inheritance continued, putting functions into a struct
Post a comment
All comments are held for moderation; basic HTML formatting accepted.