C++ instance class changing?

Ok so I'm writing a chess game- which you can see here

https://sourceforge.net/projects/ultifi-chess/

Essentially my problem is with the pawn, I have each individual piece in a class of it's own derived from a basic animation class- as each piece has very different properties,

My problem is in switching my pawn instance into a queen/bishop/castle instance. I have a control class- which controls all of the pieces on the board- and it uses an array of pointers to the base class (which have all of the virtual functions necessary) in order to simplify control of all of the pieces.

What I have tried so far is deleting the pointer within my control class and using the new keyword to have the pointer point to a new instance of a different class eg. the queen class. Unfortunately this just segfaults and my program dies. What should I do here, is there another way to change the class?

I have also considered just putting all of the characteristics of the other pieces inside of the pawn class and just changing the basic properties of the instance when you reach the end of the board- but I'm sure someone out there knows much better than me!

ultifinitus wrote:
I have also considered just putting all of the characteristics of the other pieces inside of the pawn class and just changing the basic properties of the instance when you reach the end of the board

That kind of goes against the whole polymorphic philosophy. There must be some simple error in the way you are currently doing it.

Looking at your code, you do not allocate any of your pieces using the new keyword which is probably why you are getting the seg-fault when you try to delete it.

The problem is that you can, in theory, have many pieces of the same type. So your method of creating every piece as a global variable doesn't really fit.

I would recommend that you create ALL your pieces using new and then you will be able to do the delete, new business when it comes to replacing them.
Last edited on
For example:

1
2
3
4
class piece_bishop: public animate {

  // stuff ...  
}bishop, bishop_two,bbishop,bbishop_two;

Here you are defining 4 bishops as global variables. I recommend that you don't do it that way. I would probably make a function to create your chess set and populate the control object initially.

1
2
// need to change the parameter type from animate& to animate*
main_control.activate_piece(new queen, queen_g1); 


Don't forget to delete your pieces afterwards.
Last edited on
That is EXACTLY what I was looking for! Thank you so much!
Topic archived. No new replies allowed.