0

So, i'm making program that will multiply and adds matrices. I created class matrix with constructor:

class Matrix
{
private:
    int row;
    int column;

public:
    int getRows()
    {
        return row;
    }

    int getColumns()
    {
        return column;
    }

    void print_matrix()
    {
        for(int i = 0; i < row; i++)
        {
            cout<<"\n";
            for(int j = 0; j < column; j++)
                cout<<matrix[i][j]<<"\t";
        }
    }

    Matrix(int row, int column);
};

Matrix::Matrix(int row, int column)
{
    this->row = row;
    this->column = column;

   int** matrix = new int*[row];
    for(int i = 0; i < row; i++)
        matrix[i] = new int[column];

    for(int i = 0; i < row; i++)
        for(int j = 0; j < column; j++)
            matrix[i][j] = (i+j)*2*3/4;


    for(int i = 0; i < row; i++)
        delete[] matrix[i];
    delete[] matrix;

}

at this point i dont know how to print my matrix, or work with him. In method "print_matrix" my compilator said that "'matrix was not declarated in this scope'".

  • Helpful reading: https://isocpp.org/wiki/faq/operator-overloading#matrix-subscript-op – user4581301 Jan 18 '18 at 02:44
  • 1
    make a `int** matrix` your member. And also you deleting matrix in constuctor so you won't be able to print it. Delete it in destructor instead – Alexey Andronov Jan 18 '18 at 02:45
  • Crux of the problem: `int** matrix = new int*[row];` makes a local variable. It only exists in `Matrix::Matrix(int row, int column)`. Recommend giving your text book's section on variable scope a read. If you don't have a textbook, [this list can help](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – user4581301 Jan 18 '18 at 02:46

1 Answers1

0

You are deleting the allocated matrix in the constructor itself. To make it work,

add a member int**matrix in the class. And then do the allocation in constructor and delete it in destructor.

To add it further, even if you didn't delete the matrix then you would end up with the same error. The variable you have declared and used in the constructor - it's lifetime ends when the constructor ends.

Now instead of using pointer and allocating to it, why not use vector?

In that case you will keep std::vector v; as a member variable in the class and then resize it in constructor.

v.resize(row);
for (int i = 0; i < row; ++i)
    v[i].resize(col);
user2736738
  • 30,591
  • 5
  • 42
  • 56