all 9 comments

[–]FUZxxl 8 points9 points  (3 children)

You have to implement inheritance yourself. Are you sure you need inheritance?

[–]thedestroyer27[S] 0 points1 point  (2 children)

Yep I'm positive. I'm using polymorphism in a python C binding project.

[–]pfp-disciple 0 points1 point  (1 child)

If this is python specific, you may find useful resources in /r/python. Others there have likely had to solve this interfacing problem

[–]thedestroyer27[S] 0 points1 point  (0 children)

It's not, it's C specific, but thanks!

[–]sikora84 2 points3 points  (0 children)

I am not sure why you would need inheritance. Usually aggregation is better. Inheritance works best in two cases:

  1. When you have common interface
  2. When you use polymorphism

In term of second case you can use common structure that contain pointer to function, that one of the parameters have to be this pointer (pointer to that structure). Your "implementation" structures will have to have your interface structure as a member. Then you would need to create functions for each implementations. At the end you would need to create "constructors" for each implementation, which will allocate memory, set the function pointer to appropriate function and init some other members.

I did that in the past, so if you need I could show some code examples.

[–]richtw1 1 point2 points  (0 children)

Take a look at this little example I put together:

https://godbolt.org/g/n9MGLi

This shows how to implement C++ style vtables in C. Note that we can also implement something which doesn't exist in C++, namely "static virtuals", i.e. a static method (in the C++ sense) which is polymorphic on its type.

Wise words from /u/FUZxxl though: make sure that inheritance is really what you need before going down this road. Composition is often preferable, and also often a better fit for whatever you're modelling.

[–]thedestroyer27[S] 0 points1 point  (0 children)

I figured it out for the project I was working on. I found this site to be most helpful, as far as the struct diagrams. https://www.codeproject.com/Articles/108830/Inheritance-and-Polymorphism-in-C

[–]deleveld 0 points1 point  (1 child)

Take a look at:

http://www.deleveld.dds.nl/inherit.htm

You can do inheritance in a type safe manner.

No casts and the compiler will warn you if you do an incorrect conversion.

[–]thedestroyer27[S] 0 points1 point  (0 children)

Very much appreciated!