1

I have a chess board with rows and columns in a class as below.

class ChessBoard
{
public:
       int getWidth() const;
       int getHeight() const;

       PieceType getPiece(int x, int y) const;
       void setPiece(int x, int y, PieceType Piece);
};

I then make the board as;

ChessBoard& board;

Later on I wish to access a certain tile on the board within two for loops and I'm not sure how to do it.

for(i=0;i<=ColMax, i++){//column1-->columnMax
   for(j=0;j<=rowMax-1,j++){//row1-->rowMax

      board.PieceType.i.j // Is this the correct way to access a square?
PeterSM
  • 143
  • 2
  • 6
  • 5
    Your class is called `ChessBoard` and then you have a reference to `Board` somewhere? I think you have not posted real code. Please post an MCVE. – Christian Hackl Mar 14 '17 at 16:56
  • `ChessBoard & board;` is only a reference you need to initialize it (or remove &). To access a square you probably need to use a method `getPiece` like `board.getPiece(i,j);` – Logman Mar 14 '17 at 16:59
  • 5
    It seems what you need is [a good beginners book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Some programmer dude Mar 14 '17 at 17:00
  • 1
    On an unrelated note, those conditions in the loops look suspect. If you have an array of `ColMax` elements, the last element index is `ColMax - 1`. *Also* something a good book will tell you. – Some programmer dude Mar 14 '17 at 17:00
  • Write code. Build code. Test code. Repeat. If you get stuck in build code or test code, ask a question with a [mcve]. – R Sahu Mar 14 '17 at 17:01
  • In a chess game it is extremely unlikely that you want to get a piece at `(x, y)`. If you want to check for a pawn at `a5`, you want `getPiece(a5)`, not `getPiece(a, 5)`. – Bo Persson Mar 14 '17 at 19:45
  • @BoPersson and if the chessboard is infinite (or almost infinite)? ;) – Logman Mar 16 '17 at 01:49

1 Answers1

2

When you initialize your board, you're doing it incorrectly. This code is not valid:

Board& board;

This creates a reference to an instance of a Board object. References must be initialized, so unless this is a class member declaration, you'll receive an error when you try to build this code. In order to create an instance of a ChessBoard object, you want code that looks like this:

ChessBoard board;

Given the ChessBoard interface you described, you want to access a copy of a single piece like this:

PieceType piece = board.getPiece(i, j);
Dominic Dos Santos
  • 2,623
  • 2
  • 18
  • 30