

Link: http://codepad.org/hv5E0Hev raw code | output | fork ]



jlinkous05 - C++ , pasted on Aug 18:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 /* Title: Arrays and Inheritance Author: Joseph Linkous Date: 08/11/2011 Purpose: Demonstrate logic error of casting to Foo[] from Bar[] when sizeof(Foo) != sizeof(Bar). */ #include <iostream> class Foo { public : int a ; Foo (){ a = 0 ; } }; class Bar : public Foo { public : int b ; Bar (){ b = 1 ; } }; void output ( Foo foo [], int len ){ for ( int i = 0 ; i < len ; i ++ ) //foo[i].a always equals 0, right? cout << "foo[" << i << "].a = " << foo [ i ]. a << "

" ; } int main (){ Bar bar [ 10 ]; output ( bar , 10 ); return 0 ; }



Output: 1 2 3 4 5 6 7 8 9 10 foo[0].a = 0 foo[1].a = 1 foo[2].a = 0 foo[3].a = 1 foo[4].a = 0 foo[5].a = 1 foo[6].a = 0 foo[7].a = 1 foo[8].a = 0 foo[9].a = 1