Sign in to follow this  

copying array of pointers

This topic is 4536 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

This topic is 4536 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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