c++ - Using an Array on a Polymorph design -


i starting understand polymorphism, still new topic me. here problem: have classes, enemy , bankrobber. bankrobber inherits enemy. tried make array of 10 bankrobbers. global function should use members of array something, guess worthless description, here code:

void updateenemies(enemy * p_enemy, int counter) {      for(unsigned int = 0;i < counter;i++) {          p_enemy[i].update();      }  }  int main(void) {      bankrobber enemyarray[10];      enemy * p_enemy = new bankrobber(13,1);      updateenemies(enemyarray,10);      system("pause");  };    

i apologize language mistakes. not native speaker

my actual problem: code practicing, purpose see 10 times update on console, each member of array. function updateenemys should call enemy.update functions. method type casting not want, cause not dynamicly anymore, there more enemy later on. not bankrobbers.

declaring array of bankrobber this

bankrobber enemyarray[10]; 

but acessing them through base class pointer this

enemy * p_enemy;     p_enemy[i].update(); 

wouldn't work. that's because indexing array p_enemy[i] done using offcet sizeof(enemy)
sizeof(bankrobber) bigger sizeof(enemy), p_enemy[i] end in wrong place

you should use vector of pointers instead, like

std::vector<enemy*> 

that way can use polymorphism if add pointers different objects vector. , don't need pass ugly int counter around


Comments

Popular posts from this blog

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

html - How to style widget with post count different than without post count -

url rewriting - How to redirect a http POST with urlrewritefilter -