Object slicing within a two-dimensional array in c++ -


hello having small issue storing derived type objects within 2-dimensional array of base type without loosing derived type stored in array.

for example there following base , derived class:

class base{  }  class derived: public base{  } 

there point have base object created following:

base objectb; 

then cast above object type of derived class following:

base *referencepointer = &objectb; derived *derivedpointer = static_cast<derived*>(referencepointer); 

at point working correctly (if print out type of derivedpointer of type derived).

now have 2 dimensional array of type base class initialized following:

base *basearray[5][5]; 

now input derivedpointer value array following:

basearray[x][y] = derivedpointer; 

this problem occurs stores in referencepointer becomes of base type (object slicing) , unsure how go storing referencepointer value , keep type within array of type base.

any appreciated,

thank you!

video game different types of players able move different based on there type have base functionality same.

imagine 'certain base functionality' implemented in base class. these methods can made available derived classes public or protected methods. eliminating duplicate code.

now imagine base class provides virtual method "void move(coordinatesxyz_t to, velocityxyz_t vel, accelerationxyz_t acc)".

simply adding (virtual) method same signature in derived class, each derived object can provide own unique response gaming engine's move command. there no need gaming engine know type of derived object is, correct virtual method invoked.

downcast'ing not needed. game engine can written not need care kind of derived class dealing - long derived object conforms interface. game engine invokes virtual method, result in invocation of appropriate derived object method.

the actual method can unique every member of 2 dimensional array of base pointers.

the actual method can nothing (i.e. tree not move.)

and derived class not have provide move method unless desired behaviour different base class' move method provides.


Comments

Popular posts from this blog

php - SPIP: From Tag directly to an article -

jquery - isAjaxRequest always return false -

ruby on rails - In a controller spec, how to find a specific tag in the generated view? -