Declare array in class not knowing it will be its size

How to declare an array within a class, even if you don't know what size it will be and leave it accessible by the entire program. Note This Class:

class exemplo{
public:

  int tx{0};
  int ty{0};
  int array[tx][ty]; // se eu tentar declarar aqui: não funciona porque os valores de tx e ty não foram obtidas pelo construtor ainda

  exemplo(int tempx,int tempy){
    tx = tempx;
    ty = tempy;
    int array[tx][ty]; //se eu tentar declarar aqui: compila, porem não posso acessar por fora do construtor
  }

int array[tx][ty]; //se eu tentar declarar aqui: Não funciona, dá o erro: error: invalid use of non-static data member ‘grafo::tx’
   int pgrafo[tx][ty];
              ^~

};

How to solve this problem ?

Author: silash35, 2018-05-29

1 answers

You can construct your class more or less like this:

#include <iostream>

class IntArray2D
{
    public:

        IntArray2D( int ncols, int nlinhas )
        {
            this->m_nlinhas = nlinhas;
            this->m_ncolunas = ncols;

            this->m_array = new int*[ nlinhas ];

            for( int i = 0; i < nlinhas; i++ )
                this->m_array[i] = new int[ ncols ];

        }

        virtual ~IntArray2D( void )
        {
            for( int i = 0; i < this->m_nlinhas; i++ )
                delete [] this->m_array[i];

            delete [] this->m_array;
        }

        int ler( int col, int lin )
        {
            return this->m_array[lin][col];
        }

        int gravar( int col, int lin, int dado )
        {
            this->m_array[lin][col] = dado;
        }

    private:

        int ** m_array;
        int m_ncolunas;
        int m_nlinhas;
};


int main( void )
{
    IntArray2D a( 10, 10 );

    a.gravar( 5, 5, 123 );
    a.gravar( 3, 4, 321 );
    a.gravar( 1, 5, 666 );
    a.gravar( 9, 9, 100 );
    a.gravar( 1, 1, 900 );

    std::cout << a.ler( 5, 5 ) << std::endl;
    std::cout << a.ler( 3, 4 ) << std::endl;
    std::cout << a.ler( 1, 5 ) << std::endl;
    std::cout << a.ler( 9, 9 ) << std::endl;
    std::cout << a.ler( 1, 1 ) << std::endl;

    return 0;
}

Output:

123
321
666
100
900
 1
Author: Lacobus, 2018-05-29 19:17:28