Deep copy constructor needed for an class array within another class

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • unicorn7777777
    New Member
    • Nov 2006
    • 4

    Deep copy constructor needed for an class array within another class

    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.
  • sivadhas2006
    New Member
    • Nov 2006
    • 142

    #2
    Hi,

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

    Code:
    #define NO_OF_SQUARES   64
    
    class ChessSquare
    {
       public:
          int m_nColumn;
          int m_nRow;
    };
    
    class ChessBoard
    {
       private:
       
          ChessSquare m_objChessSquare[NO_OF_SQUARES];
    
       public:
    
          ChessBoard(const ChessBoard &a_objChessBoard)
          {
             for(int i = 0; i < NO_OF_SQUARES; i++)
             {
                m_objChessSquare[i] = a_objChessBoard.m_objChessSquare[i];
             }	   	
       }  
    };
    Regards,
    M.Sivadhas.

    Comment

    • unicorn7777777
      New Member
      • Nov 2006
      • 4

      #3
      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(Ches sboard c)
      {
      this->myboard = c;
      }

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

      Class AI
      {
      Chessboard myboard;
      }
      void AI::update(Ches sboard *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

      Comment

      • sivadhas2006
        New Member
        • Nov 2006
        • 142

        #4
        Hi,

        Well,
        Can you post your full code?

        Regards,
        M.Sivadhas.

        Comment

        Working...