How to overload + to sum 2 objects that are matrix in c++?

Viewed 82

i have this class

class Matrix
{
    int size;

    std::unique_ptr<std::unique_ptr<int[]>[]>  val;

public:

    Matrix(int size1)
    {
        size=size1;
        val=std::make_unique< std::unique_ptr<int[]>[] >(size);

        ...
    }

... move constructor,move assignment operator

    Matrix& operator+(Matrix &m)
    {
        Matrix sumMatrix(size);
        for ( int i = 0; i < size; ++i)
        {
            for (int j = 0; j < size; ++j){
                sumMatrix.val[i][j]=this->val[i][j]+m.val[i][j];
            }

        }
        return sumMatrix;
    }

and main :

...
Matrix e=b+c;
    std::cout<<"e="<<std::endl;
    e.print();

and i have this error :

warning: reference to local variable 'sumMatrix' returned [-Wreturn-local-addr] Matrix sumMatrix(size);

Can someone please help me with this ??

1 Answers

Return by value, as you should for operator+ most of the time:

//   vvv--Removed &     vvvvv-----vvvvv--Const is more appropriate here
Matrix operator+(Matrix const &m) const { ... }

This will require a copy constructor, make sure to add that. Also note that you should probably collect your for-loop logic into an operator+= and simplify operator+ significantly while providing more functionality for the end-user:

Matrix& operator+=(Matrix const& m) {
  for (int i = 0; i < size; ++i) {
    for (int j = 0; j < size; ++j) {
      //vvv--No need for this-> in C++    
      val[i][j] += m.val[i][j];
    }
  }
  return *this;
}

Matrix operator+(Matrix const& m) const {
  Matrix sumMatrix{m}; // requires a copy constructor.
  sumMatrix += *this;
  return sumMatrix;
}
Related