Inheritance in C: solved exercise with composition and pointers
Inheritance in C with composition: solved exercise
If you are searching for inheritance in C, the practical approach is composition plus function pointers, since C has no native inheritance model.
This pattern lets you model simple hierarchies and runtime behavior in plain C.
Problem statement
Model a basic hierarchy:
- base type
Animalwith name andspeakbehavior, DogandCattypes that extendAnimalthrough composition,- iterate over an
Animal*array and execute polymorphic behavior.
C solution
Expected output
Common mistakes
- Copying only the base type instead of using pointers to composed objects.
- Forgetting to initialize the function pointer.
- Casting between incompatible types.
- Trying to replicate full OOP inheritance complexity in C when not needed.
Practical use
This pattern is useful for:
- callback-driven engines and libraries,
- plugin systems with a shared interface,
- reducing coupling across modules.
It is a practical design skill for systems-level C code.
Recommended next exercise
- Classes in C with struct: solved modular design exercise
- Struct in C: solved exercise with arrays of structures
- Pointer to pointer in C: solved exercise with reference updates
- All C exercises
Guided practice and next step
If you want a complete path with progressive difficulty:
FAQ
Does C have native inheritance?
No. In C, inheritance-like design is simulated with composition, pointers, and function tables or callbacks.
When should I use function pointers?
When you need swappable runtime behavior, such as strategy patterns, callbacks, or driver abstractions.
Can this pattern fully replace OOP?
Not fully. C does not provide all OOP abstractions, but this approach covers many practical modular-design cases.