Possible Duplicate:
How can I simulate OO-style polymorphism in C?
I'm trying to better understand the idea of polymorphism with examples from languages I know; is there polymorphism in C?
This is Nekuromento's second example, factored in the way I consider idiomatic for object-oriented C:
#ifndef ANIMAL_H_ #define ANIMAL_H_ struct animal { // make vtable_ a pointer so they can be shared between instances // use _ to mark private members const struct animal_vtable_ *vtable_; const char *name; }; struct animal_vtable_ { const char *(*sound)(void); }; // wrapper function static inline const char *animal_sound(struct animal *animal) { return animal->vtable_->sound(); } // make the vtables arrays so they can be used as pointers extern const struct animal_vtable_ CAT[], DOG[]; #endif
#include "animal.h" static const char *sound(void) { return "meow!"; } const struct animal_vtable_ CAT[] = { { sound } };
#include "animal.h" static const char *sound(void) { return "arf!"; } const struct animal_vtable_ DOG[] = { { sound } };
#include "animal.h" #include <stdio.h> int main(void) { struct animal kitty = { CAT, "Kitty" }; struct animal lassie = { DOG, "Lassie" }; printf("%s says %s\n", kitty.name, animal_sound(&kitty)); printf("%s says %s\n", lassie.name, animal_sound(&lassie)); return 0; }
This is an example of runtime polymorphism as that's when method resolution happens.
C1x added generic selections, which make compile-time polymorphism via macros possible. The following example is taken from the C1x April draft, section 6.5.1.1 §5:
#define cbrt(X) _Generic((X), \ long double: cbrtl, \ default: cbrt, \ float: cbrtf \ )(X)
Type-generic macros for math functions were already available in C99 via the header tgmath.h
, but there was no way for users to define their own macros without using compiler extensions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With