By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,432 Members | 790 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,432 IT Pros & Developers. It's quick & easy.

Deep copy constructor needed for an class array within another class

P: 4
Hi,
I need a deep copy constructor for a class which contains an array for another class:

class Chessboard
{
public:
ChessSquare chessSquare[64];
// copy constructor needed to copy all chessSquare and attributes

}

class ChessSquare
{
public:
int column;
int row;

}

void main (void)
{

Chessboard a1;
Chessboard a2 = a1; //deep copy needed. any suggestions for a deep copy constructor?
}

Any one can post something that can help this case? Thanks.
Nov 23 '06 #1
Share this Question
Share on Google+
3 Replies


sivadhas2006
100+
P: 142
Hi,

I think this is one way to implement the copy constructor.

Expand|Select|Wrap|Line Numbers
  1.  
  2. #define NO_OF_SQUARES   64
  3.  
  4. class ChessSquare
  5. {
  6.    public:
  7.       int m_nColumn;
  8.       int m_nRow;
  9. };
  10.  
  11. class ChessBoard
  12. {
  13.    private:
  14.  
  15.       ChessSquare m_objChessSquare[NO_OF_SQUARES];
  16.  
  17.    public:
  18.  
  19.       ChessBoard(const ChessBoard &a_objChessBoard)
  20.       {
  21.          for(int i = 0; i < NO_OF_SQUARES; i++)
  22.          {
  23.             m_objChessSquare[i] = a_objChessBoard.m_objChessSquare[i];
  24.          }           
  25.    }  
  26. };
  27.  
  28.  
Regards,
M.Sivadhas.
Nov 23 '06 #2

P: 4
ok then there's another problem.
What if i want to copy values of a chessboard that is a pointer to a value that is a normal Chessboard?
For example.

line 1: Chessboard *pBoard = CurrBoard;

line 2: Chessboard c2 = (*pBoard); // i need a deep copy of Currboard into c2..... will this work?


I know c2 = CurrBoard will work, but for some reason, when I pass a pointer through a function and try to copy it like above, it doesnt work. I get rubbish values:
*pBoard = Currboard;
AI deepblue.update(*pBoard);

Class AI
{
Chessboard myboard;
}
void AI::update(Chessboard c)
{
this->myboard = c;
}

Nor does this work:
*pBoard = Currboard
AI deepblue.update(pBoard);

Class AI
{
Chessboard myboard;
}
void AI::update(Chessboard *c)
{
this->myboard = (*c);
}

and that is with the copy constructor you have advised me as above. Do i need another copy constructor for passing pointers or something? please advise.
Thanks
Nov 23 '06 #3

sivadhas2006
100+
P: 142
Hi,

Well,
Can you post your full code?

Regards,
M.Sivadhas.
Nov 23 '06 #4

Post your reply

Sign in to post your reply or Sign up for a free account.