0

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
TBourne
  • 11
  • 4

2 Answers2

0

m_size must be a constant expression. Not necessarily const qualified.

You can try make it constexpr (but it implies to be static):

static constexpr int m_size = 2;

Or using templates:

template<size_t m_size>
class Matrix {
private:
    int *m_ptr;
public:
    Matrix(){
        new int[m_size][m_size];//testing this statement
    }   
    ~Matrix(){
        delete[] m_ptr;
    }
};

int main() {
    Matrix<2> m;
}
João Paulo
  • 6,300
  • 4
  • 51
  • 80
  • 2
    Note that the constant size requirement is only for the inner dimensions. The outer dimension of a dynamic array can be determined at runtime. – eerorika Sep 11 '19 at 17:27
  • @eerorika It always left-to-right for brackets,right-to left for asterisks and ampersands, outward for parenthesis, in this order of priority. – Swift - Friday Pie Sep 12 '19 at 08:15
0

New expressions, as well as declarations, are unfolding to the right, if brackets [] are found, and no parenthesis to change the order, and outward, if there are parenthesis.

 new int[A][B];

This means to allocate A elements of type int[B]. A can be variable, B cannot, it's part of type definition. The problem of allocating 2D array by single new expression is generally unsolvable by syntax means.

A multidimensional array isn't defined per se as a kind of type. We have objects and arrays of objects. 2D array is array of objects which are arrays. As you cannot allocate an array of objects of dynamical type, only static one, you cannot do what you intend. Instead you need a class-wrapper which would treat a simple array as a two-dimensional one by redefined operator[].

Swift - Friday Pie
  • 12,777
  • 2
  • 19
  • 42