Inheritance by Embedding
Inheritance by embedding puts a base struct as the first member of a derived struct. The derived object's address is then also the base object's address, so you can pass &derived->base — or a cast of derived — to APIs that expect the base type.
Detailed Explanation
C has no extends. The layout trick that replaces it is:
struct Animal { int hp; };
struct Dog { struct Animal base; int bark_db; };
A struct Dog d; contains an Animal at offset zero. (struct Animal *)&d and &d.base are the same address. A function void heal(struct Animal *a) can accept &d.base. Inside heal, the pointer really does address an Animal. The extra bark_db field sits after it and is invisible to heal.
This is the same convention a handwritten vtable uses. It is also how some kernels build object trees. It is not a subtype relationship the compiler understands. There is no implicit conversion. You write the cast or the &d.base every time. A function that takes a struct Dog * will not accept a struct Animal * going the other way, and a down-cast is a promise you make with no check.
Embedding at offset zero is required for the cast of the outer pointer to be valid. If you write struct Dog { int id; struct Animal base; };, then (struct Animal *)&d points at id, not at the animal. Use &d.base always if you want to be allowed to put fields first; use the cast only when the base is first and you have documented that as an invariant.
Multiple "inheritance" is possible by embedding two bases, but only one of them can be at offset zero. The second is a member at a non-zero offset, and every up-cast to that second base must go through the member. This gets messy quickly. Prefer composition: store the second part as a named member and do not pretend the dog is both types.
Initialization is manual. dog_init calls animal_init(&d->base) and then sets bark_db. Cleanup runs in reverse. There is no constructor chain.
Code Examples
#include <stdio.h>
struct Animal {
int hp;
};
struct Dog {
struct Animal base; /* offset 0: Dog* and Animal* alias */
int bark_db;
};
static void heal(struct Animal *a, int n)
{
a->hp += n;
}
int main(void)
{
struct Dog d = { .base.hp = 10, .bark_db = 80 };
heal(&d.base, 5);
printf("%d %d\n", d.base.hp, d.bark_db); /* prints: 15 80 */
return 0;
}#include <stdio.h>
#include <stddef.h>
struct Animal { int hp; };
struct Dog { struct Animal base; int bark_db; };
int main(void)
{
printf("%zu\n", offsetof(struct Dog, base)); /* prints: 0 */
return 0;
}Common Gotchas
Prefer `&d.base` over a cast
it stays correct if someone later inserts a field above the base.
Copying the base out of the derived object slices
`struct Animal a = d.base;` drops `bark_db` and any vptr that was meant to stay with the dog.