canesin
canesin

Reputation: 1997

Not working matrix operator+ overloading

I'm trying to make a example (just example! I know it leaks) app to learn operator overloading in C++, but I get the value of zero to the elements of the sum.... I suspect that the problem is int the copy constructor.

The Detailed implementation is below:

    class Matrix{
    public:
        Matrix(int row, int col);
        Matrix(const Matrix& src);
        float& set(int row, int col);
        float get(int row, int col);
        const Matrix & operator+(const Matrix& rhs);

    private:
        float* data;
        int nrow;
        int ncol;
};

Matrix::Matrix(int row, int col){
    nrow = row;
    ncol = ncol;
    data = new float[nrow*ncol];
}

Matrix::Matrix(const Matrix& src){
    nrow = src.nrow;
    ncol = src.ncol;
    data = new float[nrow*ncol];

    for(int i = 0; i < nrow*ncol; i++){
        data[i] = src.data[i];
    }
}

float& Matrix::set(int row, int col){
    return data[row*ncol+col];
}

float Matrix::get(int row, int col){
    return data[row*ncol+col];
}

const Matrix & Matrix::operator+(const Matrix& rhs){

    if (this->nrow == rhs.nrow && this->ncol == rhs.ncol){
        Matrix* m = new Matrix(rhs.nrow, rhs.ncol);
        for(int i=0; i< nrow*ncol; i++){
            m->data[i] = data[i] + rhs.data[i];
        }
        return *m;
    } else {
        throw -1;
    }
}

#include <iostream>

using namespace std;

int main ()
{
    Matrix A(1,1);
    Matrix B(1,1);

    A.set(0,0)=1;   
    B.set(0,0)=2;

    cout << A.get(0,0) << endl;
    cout << B.get(0,0) << endl;

    Matrix C = A + B; // Marix C(A+B);
    cout << C.get(0,0) << endl;

    return 0;
}

Upvotes: 1

Views: 221

Answers (1)

Mat
Mat

Reputation: 206689

Matrix::Matrix(int row, int col){
    nrow = row;
    ncol = ncol;
    data = new float[nrow*ncol];
}

There's a typo in there that results in your code having undefined behavior.

Fix it with:

    ncol = col;

(Make sure you turn you compilers warning/diagnostics level to the maximum, GCC catches this.)

You're leaking your float[]s too, so your code isn't complete. Don't forget to add proper destructors, and always follow the rule of three.

Upvotes: 5

Related Questions