0
Polymorphism and Inheritance in the C struct data type
Can you apply polymorphism and inheritance to the C struct data type? If so, does it work similar to other languages such as C++? What are the differences? I.e. look at this code: typedef struct student_struct { int id; char major[255]; double year; } student; If I make a variable of student type named student1 (student student1;), would student1.id, student1.major, and student1.year demonstrate inheritance/polymorphism of the struct data type?
3 odpowiedzi
+ 3
Polymorphism means that certain behavior at runtime is depended on the actual type an object has at runtime which is not always known at compile time. Hence this can only work for languages which allow objects to have behavior attached to them like C++ having methods of classes. Secondly in order for polymorphism to work obviously there needs to be some sort of type information at runtime. Which is not available in C. All types you declare in C are only existent during development of your program. This is actually almost the same in C++ with the small difference that C++ objects with virtual methods (which want to use polymorphism) have an additional hidden property which is a pointer to their respective virtual table. That is the sort of minimum type information you need for polymorphism.
Inheritance of methods is obviously not possible in C. You can however sort of inherit properties of a struct to another struct by nesting them. But you won't have any compile time type checking when using that with
+ 2
... functions.
Your examples do not demonstrate inheritance/polymorphism. They are just accessing properties of a struct.
0
@Hape thanks, that gives a lot of clarification on the subject. I was confused earlier, especially since as you mentioned, you can "sort of inherit properties of a struct to another struct by nesting them" - which is centered around how I thought before. However, C does not support actual inheritance/polymorphism since there's no compile type checking, custom object behavior, or existence of classes. I understand this concept much better now, thanks.