4 ms·
Disagree C has classes. No "class" and no inheritance or polymorphism C has perfectly good inheritance: struct child { struct parent p; //
by cperciva 17y ago
Disagree C has classes. No "class" and no inheritance or polymorphism
C has perfectly good inheritance:
struct child {
struct parent p;
// new variables go here
}
struct child foo;
struct parent * bar = &foo; // perfectly valid C
- mkramlich 17y agoLooks like composition and a struct alias, not inheritance to me. Is my C that rusty? For example, say that the "struct parent" type (which in your example has no members) had a member named z. In your example, I expect to be allowed to do something like this: (*bar).p.z which is composition. But not: (*bar).z which would be member inheritance. Because bar/foo/child all lack a z member. Only "parent" has a z member. Am I wrong?
- cperciva 17y agoIt's valid C to cast a structure to the type of its first element. So in the example of struct child { struct parent { int z; } p; } foo; you can access foo.p.z but not foo.z -- but you can access (struct parent *)(&foo)->z, so you can pass foo to anything which expects a struct parent.
- mkramlich 17y agoI'll assume you're right. Thanks for pointing that out. Your C sounds fresher than mine. I used it heavily from 90-95 or so but later moved on to higher languages like Java and Python. If what you point out about the syntax is accurate, I find that to be a counter-intuitive design decision.
- mhansen 17y agoIt works because C structs are just contiguous bits of memory, interpreted as various fields. A pointer to a struct points to the start of that contiguous bit of memory. Child Struct: +---------------+-----------------+ | parent struct | child fields | +---------------+-----------------+ ^ \--- pointers to the struct point at the start You can cast this child struct to a parent struct, which is like saying 'interpret memory starting here as a 'parent' struct'. This works: The memory from location to location+sizeof(parent) IS a parent struct. The child fields following the parent struct are simply ignored.
- cperciva 17y agoIt works because C structs are just contiguous bits of memory, interpreted as various fields Well... almost. C structs can have internal padding -- but the C standard doesn't allow padding before the first element, so that first element is guaranteed to begin at the beginning of the struct.
- mhansen 17y agoThanks! You learn something every day :)