This question already has an answer here:
- Object-orientation in C 18 answers
Is it possible to model inheritance using C? How? Sample code will help.
Edit: I am looking to inherit both data and methods. Containership alone will not help. Substitutability - using any derived class object where a base class object works - is what I need.
I've used an object system in C that used late-bound methods, which allowed for object-orientation with reflection.
You can read about it here.
You can definitely write C in a (somewhat) object-oriented style.
Encapsulation can be done by keeping the definitions of your structures in the .c file rather than in the associated header. Then the outer world handles your objects by keeping pointers to them, and you provide functions accepting such pointers as the "methods" of your objects.
Polymorphism-like behavior can be obtained by using functions pointers, usually grouped within "operations structures", kind of like the "virtual method table" in your C++ objects (or whatever it's called). The ops structure can also include other things such as constants whose value is specific to a given "subclass". The "parent" structure can keep a reference to ops-specific data through a generic
void*
pointer. Of course the "subclass" could repeat the pattern for multiple levels of inheritance.So, in the example below,
struct printer
is akin to an abstract class, which can be "derived" by filling out apr_ops
structure, and providing a constructor function wrappingpr_create()
. Each subtype will have its own structure which will be "anchored" to thestruct printer
object through thedata
generic pointer. This is demontrated by thefileprinter
subtype. One could imagine a GUI or socket-based printer, that would be manipulated regardless by the rest of the code as astruct printer *
reference.printer.h:
printer.c:
Finally, fileprinter.c:
It is very simple to go like this:
But if you use MS extension (in GCC use
-fms-extensions
flag) you can use anonymous nestedstruct
s and it will look much better:Since early versions of C++ were mainly a preprocessor that converted into C, it's deinitely possible.
Yes, you can emulate heritance en C using the "type punning" technique. That is the declaration of the base class (struct) inside the derived class, and cast the derived as a base:
But you must to declare the base class in the first position in you derived structure, if you want to cast the derived as base in a program:
In this snippet you can use the base class only.
I use this technique in my projects: oop4c
This link might be useful -> link
Basic example will be like follow