I'm working on a program that has a class Board, and two inherited classes that will implement different games, but I'm having problems with setting up the initial Board class. The problem is that I don't know how to make it so the board array in the protected section of the Board.h file takes on the values input in a and b in the main.cpp file.

Here's my main.cpp

#include <iostream>
#include "Board.h"

using namespace std;

int main()
{
    Board Game;
    int a, b;
    cout << "enter a: ";
    cin >> a;
    cout << endl << "enter b: ";
    cin >> b;
    cout << endl;
    Game.set_board(a,b);
    Game.display();

    return 0;
}

my Board.cpp

#include "Board.h"
#include <iostream>

using namespace std;

Board::Board()
{

}

void Board::display()
{
    for (int i = 0; i < width; i++)
    {
        for (int j = 0; j < height; j++)
        {
            cout << board[i][j] << " ";
        }
        cout << endl;
    }
}

void Board::set_board(int a, int b)
{
    width = a;
    height = b;

    int num = 1;

    for (int i = 0; i < width; i++)
    {
        for (int j = 0; j < height; j++)
        {
            board[i][j] = num++;
        }
    }
}

and my Board.h file

#ifndef BOARD_H_INCLUDED
#define BOARD_H_INCLUDED

class Board
{
    public:
    Board();
    void display();
    void set_board(int, int);

    protected:
    int height, width;
    int board[4][4];
};

#endif // BOARD_H_INCLUDED

Instead of: int board[4][4];
Replace with: int** board;
Now we can dynamically allocate space for the 2D board array.

In set_board(), we need to do the dynamic allocation like so:

// First allocate for the first dimension
board = new int*[height];

// Now allocate for the second dimension
for( int i = 0; i < height; i++ ) {
   board[i] = new int[width];
}
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.