I have seen this being done before.
#include "stdio.h"
#define FRUIT_COLOR_RED 1
struct fruit {
char* name;
};
struct apple {
struct fruit base;
int color;
};
void printFruit(struct fruit *f) {
printf(f->name);
}
int main(int argc, char** argv) {
struct apple a;
a.base.name = "apple";
a.color = FRUIT_COLOR_RED;
printFruit((struct fruit*)&a);
return 0;
}
This works because struct fruit is the first member of struct apple and the two structures are aligned in memory.
|-- 4 or 8 bytes(char*) --| => struct fruit in memory
|-- 4 or 8 bytes(char*) --|-- 4 or 8 bytes(int) --| => struct apple in memory
The first 4 or 8 bytes(depending on 32 bit vs 64 bit respectively) are the same length and type so you can cast a struct apple* to a struct fruit* and because they line up in memory, it reads the members of struct fruit.
I don't know if this is good practice and I would avoid it. I love the simplicity of C, but why not use a language that has these constructs built in such as C++.
Too implement Object Orientation features in C is going to mean more lines of code and more maintenance.
Also if the code doesn't build I wrote it now in notepad, but the concept is there. Don't have a C compiler on me at the moment :-(.