Polymorphism and Inheritance in the C struct data type | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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?

5th Jun 2021, 7:38 AM
Nova
Nova - avatar
3 Answers
+ 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
5th Jun 2021, 7:54 AM
Hape
Hape - avatar
+ 2
... functions. Your examples do not demonstrate inheritance/polymorphism. They are just accessing properties of a struct.
5th Jun 2021, 7:55 AM
Hape
Hape - avatar
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.
7th Jun 2021, 1:58 AM
Nova
Nova - avatar