mercredi 11 septembre 2019

using "new" command to allocate 2d array inside class constructor in c++

I'm trying to write a matrix class of my own using c++. I want to allocate heap memory for this purpose using new operator. Following is class snippet and this throws error:

  class Matrix
    {
        private:
            int *m_ptr;
            const int m_size;
        public:
            Matrix():m_size(2)
            {
                new int[m_size][m_size];//testing this statement
            }   

            ~Matrix()
            {
                delete[] m_ptr;
            }
    };

error:

main.cc: In constructor ‘Matrix::Matrix()’:
main.cc:11:26: error: array size in new-expression must be constant
    new int[m_size][m_size];//testing this statement
                          ^
main.cc:11:26: error: ‘this’ is not a constant expression

Aucun commentaire:

Enregistrer un commentaire