3 ms·
I have not read the book. > However, C is not C++ and is not intended for providing all OOP features like inheritance. There are parts of the ISO C standard s
by quelsolaar 4y ago
I have not read the book.
> However, C is not C++ and is not intended for providing all OOP features like inheritance.
There are parts of the ISO C standard specifically included to allow for inheritance. Consider:
typedef struct{
int x;
}struct_a;
typedef struct{
struct_a inherited;
int y;
}struct_b;
void function(struct_a *s)
{
s->x = 0;
}
Here struct_b inharates struct_a. You can call the function with either a pointer to struct_a or struct_b (either by casing or void pointer), because the standard specifically states that there can be no padding before the first member of a structure, so that the first member of a structure should have the same pointer as the structure itself. This part of the spec was written with the use case of inheritance in mind. (there is some people who don't read the spec that way, but this is the intention)
Sorry for being nitpicky... but that's pretty much what we do in the wg14....
- orlp 4y agoDoesn't this violate strict aliasing? E.g. what if we do this? void foo(struct_a *a, struct_b *b) { a->x = 0; b->x += 1; a->x = 0; } Strict aliasing allows the compiler to elide the second a->x = 0. But if we use your inheritance scheme using casting of pointers, we could have a == b.