Sign in to follow this  
xidis

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 this post


Link to post
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this