Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

4
  • The example is incomplete. There is no explanation for how to implement a new class with different members (besides just the int). In this case, it seems that all of the "polymorphic" objects will have the same int member. What if you want to define classes with different members? I think in that case your struct should have a void pointer to data members, instead of a concrete int. Commented Jun 25, 2018 at 19:55
  • @user2445507 the example implements a vtable which calls functions at runtime, exactly what c++ would do behind the scenes if you create a class. Commented Oct 3, 2018 at 8:00
  • @NiclasLarsson In C++ it is possible to create another class inheriting the pure virtual functions, but with different member variables. Then, the virtual function implemented in that class can use those member variables. This is a key aspect of polymorphism. The example does not demonstrate how to do this. For this example, you might as well just use function pointer. Commented Oct 5, 2018 at 19:29
  • @user2445507 Check out my answer. The only thing that you need is that both structs have the common fields in the same places. If a common field is on the 3rd spot in parent class, it must be on the 3rd spot in the child class. You do this with all the fields that 2 classes share and you put the common fields in the beginning of the child struct. The same way vTable pointer should be on the same spot in both classes. That's how you can hack polymorphism into C. Commented Dec 9, 2022 at 5:33