# copying array of pointers

## Recommended Posts

xidis    127
I am writing a chess game. I have got everything working except for calculating check and making sure the players next move gets their king out of check. In order to do this, i need to test for check at the begginning part of a players turn and then test again at the end, to see if there move got them out of check. If it did, then the game goes on, but if it didnt, I throw an error and the player has to make another move. The easiest way I thought of doing this is creating a backup board which can be loaded if the move still leaves the king in check, however, my program keeps crashing whenever i try to copy the array which holds pointers to my pieces(using polymorphism). My question is how do I copy such an array, not just the pointers, but the data they point to?

##### Share on other sites
Fruny    1658
You can use the object's copy constructor in a new expression.

for(int = 0; i< array_size; ++i)   new_array[i] = new Whatever( *old_array[i] );

If the objects have varied types (polymorphism), then you should provide them with a virtual clone method:

class Base{public:   virtual Base* Clone() = 0;   virtual ~Base() {} // for polymorphic destruction};class Derived1 : public Base{public:   Base* Clone() { return new Derived1(*this); }};class Derived2 : public Base{public:   Base* Clone() { return new Derived2(*this); }};...for(int = 0; i< array_size; ++i)   new_array[i] = old_array[i]->Clone();

Don't forget to delete the objects eventually.