Hello,
Suppose I have a chess game. I make a nice class to handle an entire player's pieces:

class c_ChessTeam
{
    private:
        // all pieces derive from class c_ChessPiece
        c_Rook Rook[2];
        c_King King;
        c_Queen Queen;
        c_Bishop Bishop[2];
        c_Knight Knight[2];
        c_Pawn Pawn[8];
    public:
        . . .
};

But what if I'm playing by the rule that, when a pawn has reached the edge of the board, they turn into a different piece (for example, a knight)? Then my pawn has to change classes into a c_Knight object. To avoid this, I could do this:

class c_ChessTeam
{
    private:
        c_ChessPiece Rook[2];
        c_ChessPiece King;
        c_ChessPiece Queen;
        c_ChessPiece Bishop[2];
        c_ChessPiece Knight[2];
        c_ChessPiece Pawn[8];
    public:
    . . .
};

Now, all my pieces have no unique "rules" on how they act, and I've essentially created a checkers game. I could code the c_ChessPiece class to have all the information for each of the unique pieces, but that could lead to the program running not so smooth.

What would someone do in this situation, where they need their object to essentially change classes?

How about an array (size 16) of c_ChessPiece pointers. That way you can have up to 16 c_ChessPieces but in any combination you want. If you have a virtual move() function in the c_ChessPiece class that is overridden by each derived class then each c_ChessPiece pointed to by the c_ChessPiece pointers can express it's own movement. You can keep track of the total number of pieces available to account for captured pieces. You can overwrite a specific pointer with another to change from one derived class to another. You can keep track of the actual and maximum number of each type of piece you have to prevent having more than 1 King or 9 Queens, etc.

>>Now, all my pieces have no unique "rules" on how they act

Well it should if c_ChessPiece has proper virtual functions? Btw, not a fan of the class-prefix.

For example take a look at this interface. A ChessPiece should at least have some uniform functions, like move and such. So what you should be doing is having an array of chesspiece pointers. And inside the constructor, initialize them to their proper piece. And when time comes to promote the pawn, all you do is create a new Knight piece( assuming use picks knight ), then copy the pawn's information into the newly created knight piece, for example its location and stuff. Then just delete the pawn and add the new chess piece which points to a knight. Make sense?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.