In which condition is the statement in the title true? For which version of C and with which compiler options?
My question origins from Steve's statement: "You should notice now - that since our FooSubclass's first member is, in fact, a Foo struct - that any reference to a FooSubclass is also a valid reference to a Foo - meaning it can be used as such pretty much anywhere. " (MVC implemented in pure C) It's the first time I see anyone mention such a thing. The following code raises warnings hence my questioning about the validity of this statement.
#include <stdio.h>
#include <assert.h>
typedef struct Foo {
int weight;
} Foo;
Foo foo_init(int weight) {
Foo t;
t.weight = weight;
return t;
}
int foo_weight(const Foo *this) {
return this->weight;
}
typedef struct Bar {
Foo base;
int size;
} Bar;
Bar bar_init(int weight, int size) {
Bar w;
w.base = foo_init(weight);
w.size = size;
return w;
}
int bar_weight(const Bar *this) {
return foo_weight(this);
}
int bar_size(const Bar *this) {
return this->size;
}
int main (int argc, char *argv[]) {
Foo t = foo_init(22);
Bar w = bar_init(20,14);
assert(foo_weight(&t) == 22);
assert(bar_weight(&w) == 20);
assert(bar_size(&w) == 14);
return 0;
}
Result:
> gcc main.c
main.c: In function 'bar_weight':
main.c:31:20: warning: passing argument 1 of 'foo_weight' from incompatible pointer type [-Wincompatible-pointer-types]
return foo_weight(this);
^~~~
main.c:14:5: note: expected 'const Foo * {aka const struct Foo *}' but argument is of type 'const Bar * {aka const struct Bar *}'
int foo_weight(const Foo *this) {