I am trying to add two matrices and get error when I add two matrices in the line rslt = m1+m2 using operator overloading. Both m1 and m2 are matrix classes.

Here is the code:

int main(int argc,char *argv[]) 
{
	matrix * rslt;

	//matrix *m1 = new matrix();
	matrix m1;
	m1.initMatrix(10,10,0,1);
	m1.print();

	//matrix *m2 = new matrix();
	matrix m2;
	m2.initMatrix(10,10,10,1);
	m2.print();

	rslt = m1 + m2;
	//m1.printResult();
	cout<<"done"<<endl;

}
matrix& matrix::operator+(const matrix& b)
{
	int rows = this.getRowSize();
	int cols = this.getColSize();
	int seed = this.getSeed();
    	matrix *rslt = getResultMatrix(rows, cols, seed); 
	for(int i=0; i<rows; i++)
   	{
		double res = 0.0;
   		for(int j=0; j<cols; j++)
      		{
         		      rslt.m[i][j] = this.m[i][j]+b.m[i][j];
      		}
      		
   	}
	return rslt;
}

I think it's because you declared rslt as a pointer.Try declaring it as an object matrix rslt.

I changed it like you said. I tried similar operation with operator= Just to make sure
It works fine.
But when I use operator+ it gives error.

matrix matrix::operator=(const matrix & rhs)
{
    int iter = rhs.getIterations();
    this.setIteations(iter);
    return *this;
}
matrix matrix::operator+(const matrix & b)
{
    int ** result;
    int rows = this.getRowSize();
    int cols = this.getColSize();
    int seed = this.getSeed();

        matrix *rslt = getResultMatrix(rows, cols, seed); 

    for(int i=0; i<rows; i++)
    {
        for(int j=0; j<cols; j++)
            {
               rslt.m[i][j] = this.m[i][j]+b.m[i][j];
            }
    }
    return rslt;
}
int main(int argc,char *argv[]) 
{
    matrix rslt;

    matrix m1;
    m1.initMatrix(10,10,5,1);
    m1.print();

    matrix m2;
    m2.initMatrix(10,10,10,2);
    m2.print();
        // this works
    m1 = m2;
        // gives error here
        rslt = m1+m2; 
}

However when I add using operator+ overload, it gives error. Please can someone tell me what is wrong?

as caut_baia stated you are returning a pointer but your function is defined to return just an object
change this

return rslt;

to this

return *rslt;

as caut_baia stated you are returning a pointer but your function is defined to return just an object
change this

return rslt;

to this

return *rslt;

I tried and it does not work. Is there any other way of coding to add matrices and get around this?

Could you post the full error message?

int rows = this.getRowSize();
int cols = this.getColSize();	
int seed = this.getSeed();

Isn't this a pointer? so acces should be made with a -> instead of a . .
Try it .. though i'm not sure about it.

Thanks. I got it solved. I repalced -> with . and it worked.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.