dynamic 2d array allocation as instance variable

I would like to declare a dynamically sized 2d array as an instance variable. I'm declaring it using variables that are defined as constants. The constructor is initializing these constants and then is going to initialize the array. The compiler does not allow for this type of dynamic allocation. What can I do so that I don't have to pass the array back and forth as a local variable?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

    class GameOfLife
   {
   private:
      const int interval;              // the number of evolutions between grid displays
      const int rows;                  // the number of rows in the game grid
      const int cols;                 // the number of columns in the game grid
      int cell[rows][cols];           // every cell's number of neighbors
      bool alive[rows][cols];         // every cell's biological status 
   
   
    public:
      GameOfLife (int interval, int rows, int columns);
      ~GameOfLife();
      void updateGrid(int rows, int cols);
      void updateNeighborCount(int x, int y, int rows, int cols);
      int countNeighbors(bool neighbor[][]);
      void evolve(int rows, int cols);
      bool GameOfLife::liveCell(int y, int x);
      void GameOfLife::setCellStatus(int y, int x, bool status);
   
   }; // end class definition

/********************
   Contstructor
********************/
    GameOfLife::GameOfLife(int inter, int r , int c)
   {
      interval = inter;
      rows = r;
      cols =c;
   
      for (int x = 0; x < cols; x++) 
      {
         for (int y = 0; y < rows; y++)
         {
            cell[y][x] = 0;
            alive[y][x] = false;
         }
      }
   
      for (int i =0; i < cols; i++)
      {
         for (int j = 0; j < rows; j++)
         {
            countNeighbors(i, j, rows, cols);
         }
      }
     
   }

Last edited on
You need to make cell and alive int** and bool** and dynamically allocate the arrays yourself in the constructor using array new. Then write a destructor that frees the memory, and make the class non-copyable unless you write a copy constructor and assignment operator.
Topic archived. No new replies allowed.