c++ - Some trouble with derived classes -


this question has answer here:

i trying implement functions , classes below, output arr[i].x wrong. correctly arr[0].x = 0 , arr[1].x = 0, arr[2].x not return 0. ideas why?

class base { public:   int x; };  class derived : public base { public: int y; void init(base *b); void foo(); };  void derived :: init(base *b) {   for( int = 0; < 3; ++i) {     b[i].x = 0;   } }  void derived :: foo() {    derived arr[3];   init(arr);   for( int = 0; < 3; ++i) {   cout<<"b["<<i<<"] "<<arr[i].x;   } }   int main() {     derived der;     der.foo();     return 0; } 

void derived :: foo() {      derived arr[3];     init(arr); 

a pointer derived, derived*, passed function init(base *b). happens next instead of moving sizeof(derived)=8 in table function move sizeof(base)=4 results in initialization of x member first , second derived in array , y of first derived, not x of last derived.

pointer arithmetic done based on size of type of pointer

consider memory layout (on x64):

in derived::foo():

derived arr[3];  0x7fffffffe310  // 1st derived, address of arr[0].x +8 =  0x7fffffffe318  // 2nd derived, address of arr[1].x +8 =  0x7fffffffe320  // 3rd derived, address of arr[2].x 

but in derived::init( base* b):

b[0].x = 0x7fffffffe310  // set arr[0].x 0 +4 = b[1].x = 0x7fffffffe314  // set arr[0].y 0 +4 = b[2].x = 0x7fffffffe318  // set arr[1].x 0 

thus, have set arr[0].x 0, arr[1].x 0 , incidentally arr[0].y 0. not want. solution change derived::init to

void derived::init( derived *d) {   for( int = 0; < 3; ++i) {     d[i].x = 0;   } } 

or better, following principle of more generic programming:

template < size_t n> void derived::init( derived (&d)[n] ) {     for( int = 0; < n; ++i) {         d[i].x = 0;     } } 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -