I have a question about C and attempting to mock a partial type of “inheritance”, only in accessing members of structures. Look at the following example:
#pragma pack(push,1)
typedef struct foo
{
int value;
int value2;
}foo;
typedef struct foo_extended
{
// "inherits" foo
int value;
int value2;
// "inherits" foo stops
//we also have some additional data
float additional;
}foo_extended;
#pragma pack(pop)
//! This function works for both foo types
void workboth(void* objP)
{
foo* obj = (foo*)objP;
obj->value = 5;
obj->value2 = 15;
}
//! This works only for the extended
void workextended(foo_extended* obj)
{
obj->value = 25;
obj->value2 = 35;
obj->additional = 3.14;
}
int main()
{
foo a;
foo_extended b;
workboth(&a);
workboth(&b);
workextended(&b);
return 0;
}
This works in my system but my question is whether this can be portable as long as there is correct packing of the involved structures (depending on the compiler). I suppose it would need #ifndefs correcttly invoking the tight packing in other compilers too.
Of course the obvious problem is total lack of type checking and putting all of the responsibility of correct usage to the programmer but I am wondering if this is portable or not. Thanks!
P.S.: Forgot to mention that the standard I attempt to adhere to is C99
By reading 6.7.2.1/12 and /13 in the C99 draft, I think it can be assumed that two different structs with the same initial members are compatible up to the first different member.
6.7.2.1/12
6.7.2.1/13