Can I include or declare a function inside a structure? I am trying to achieve polymorphism in C. If defining a function isn't the correct way to do it, what other methods can I use?
Asked
Active
Viewed 4,110 times
2
-
1You can't have `struct`s inherit from other `struct`s, so subclass-polymorphism isn't possible in vanilla C (without doing it yourself). – voithos Nov 17 '14 at 01:51
-
1@voithos Actually that is possible in plain C. – 2501 Nov 17 '14 at 01:53
-
Polymorphism in C: just using function pointer and casting. – S Dao Feb 15 '16 at 11:48
1 Answers
4
Polymorphism as a feature of object-oriented languages is not available in C. Neither are encapsulation and inheritance - the language does not have the corresponding features.
This does not mean, however, that it is impossible to model the corresponding behavior with the regular features of C: it is possible to build a library that lets you produce behavior that looks like polymorphism, for example, by using arrays of function pointers.

Sergey Kalinichenko
- 714,442
- 84
- 1,110
- 1,523