Overloading + operator

Hey guys. I have been working on an assignment where I have to add three objects of a class Matrix. The class should have the flexibility to add more than two oprands without changing any operand on Left hand side of the '=' operator.
1
2
Matrix obj1, obj2, obj3, obj4
Obj1=obj2+obj3+obj4


I am using the following code for this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Matrix Matrix::operator + (Matrix &obj)
{
	if((this->Columns == obj.Columns) && (this->Rows == obj.Rows))
	{
		for(int i=0;i<obj.Rows;i++)
		{	
			for(int j=0;j<obj.Columns;j++)
			{
				*(*(this->MatrixData+i)+j) = *(*(this->MatrixData+i)+j) + *(*(obj.MatrixData+i)+j);
			}
		}
	}
	
	else
	{
		cout<<"This task is not possible. Because the size is not same"<<endl;
		return (*this);
	}

	return (*this);
}


the problem is that it is just adding only 2 operands. How can I add more?
the problem is that it is just adding only 2 operands. How can I add more?


It only needs to add 2 operands. However, the prototype should be:
Matrix Matrix::operator+(const Matrix& obj) const, so that it may be used with temporary objects (as well as accurately portray what you want to do with the original objects: which is to not modify them.)

obj1 = obj2 + obj3 + obj4; is parsed as:
obj 1 = (obj2 + obj3) + obj4;
The first addition produces a temporary Matrix object which is added to obj4 in the second invocation of operator+.
You made my day Man. :D
That was what I was looking for.
Thanks alot buddy.
Topic archived. No new replies allowed.