0

I'm currently implementing a matrix class and I have a problem overloading + operator.

The detailed implementation is below:

**matrix.h:**

#pragma once
#include <iostream>
using namespace std;

template <typename t>
class Matrix
{
    int n, m;
    t **data;
public:
    Matrix(int, int, t);
    Matrix(Matrix &);
    ~Matrix();

    Matrix<t> operator+(const Matrix<t> &);
};

template<typename t> Matrix<t>::Matrix(int n = 1, int m = 1, t data = 0)
{
    this->n = n;
    this->m = m;
    this->data = new t*[this->n];

    for (int i = 0;i < n;++i)
    {
        this->data[i] = new t[this->m];
        for (int j = 0;j < m;++j)
        {
            this->data[i][j] = data;
        }
    }
}

template<typename t> Matrix<t>::Matrix(Matrix &m)
{
    this->n = m.n;
    this->m = m.m;
    this->data = new t*[this->n];

    for (int i = 0;i < n;++i)
    {
        this->data[i] = new t[this->m];
        for (int j = 0;j < this->m;++j)
        {
            this->data[i][j] = m.data[i][j];
        }
    }
}

template<typename t> Matrix<t>::~Matrix()
{
    for (int i = 0;i < this->n;++i)
        delete[] data[i];
    delete[] data;
}

template<typename t> Matrix<t> Matrix<t>::operator+(const Matrix<t> &x)
{
    if (x.n == n && x.m == m)
    {
        Matrix<t> temp(n, m, 0);
        for (int i = 0; i < n;++i)
            for (int j = 0; j < m;++j)
            {
                temp.data[i][j] = data[i][j] + x.data[i][j];
            }
        return temp;
    }
    else
    {
        return *this;
    }
}



**main.cpp:**

#include "matrix.h"

int main()
{
    Matrix<double> x(1, 1, 2); // defines a matrix 1x1 with all elements 2
    Matrix<double> y(1, 1, 3); // defines a matrix 1x1 with all elements 3
    Matrix<double> z(1, 1, 0); // defines a matrix 1x1 with all elements 0
    z=x+y;
}

I get a runtime error when a + operation is to be done. What could be the problem here?

A6EE
  • 141
  • 1
  • 8
  • 1
    What runtime error? segfault? – Kenney Nov 19 '15 at 00:48
  • Just "matrix.exe has stopped working!" and two options: Debug or Close Program. Is that a runtime error? – A6EE Nov 19 '15 at 00:50
  • Yes, but depending on the environment you get different kinds, some more informative than others. I'm getting a core dump on Cywin. On Linux I'm getting `*** Error in './a.out': free(): invalid pointer: 0x0000000001be6120 ***` – Kenney Nov 19 '15 at 00:51
  • 3
    You haven't defined an assignment operator. – Anon Mail Nov 19 '15 at 00:53
  • 1
    [Rule of three for the win.](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three) – user4581301 Nov 19 '15 at 01:09

0 Answers0