copying array of pointers

Started by
0 comments, last by Fruny 18 years, 9 months ago
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?
Advertisement
You can use the object's copy constructor in a new expression.

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


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 = old_array->Clone();


Don't forget to delete the objects eventually.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

This topic is closed to new replies.

Advertisement