PeterSM
PeterSM

Reputation: 153

Accessing class members C++

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?

Upvotes: 1

Views: 95

Answers (1)

Dominic Dos Santos
Dominic Dos Santos

Reputation: 2703

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);

Upvotes: 2

Related Questions