Possible Duplicate:
Can a pointer to base point to an array of derived objects?
I am practicing what learned and I tried the folowing:
#include <iostream>
struct S {
S() : val(0) {}
int val;
};
struct D : S {
D() : val(1) {}
int val;
};
void f(S *s) {
for (int i = 0; i < 5; i++, s++)
std::cout << s->val;
}
int main() {
D d[5];
f(d);
}
What I find weird is that the output is 01010 instead of 11111 like I expected. So it seems to be getting the val member from the S class instead of the D class on every other loop. But why?
Because
s++increments the pointer by thesizeof(S), notsizeof(D), yetsactually points to the array ofDat run-time.S::valof the first array element (which is 0),D::valof the first element (which is 1),S::valof the second element (which is 0)This is essentially an undefined behavior. If your classes looked differently (or a platform with different alignment was used), you’d receive different and even more baffling results.
If you don’t need polymorphism, just declare the function to receive an array of
D(notS). If you do need the polymorphism, you should consider using an array of (smart) pointers, instead of the array of concrete elements (and access the data through virtual functions instead of direct field access).