Overloading Operators

Hey guys, I am writing a C++ program, overloading the operators to multiply a matrix with a scalar..

Example:

M = [1 1, 2 2];
N = M * -1;

Now, The second line's code looks like this:
 
newMatrix = mMatrix * scalar;

I know that the compiler will first run the multiplication overload, here's my script for that:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Matrix& Matrix::operator*(double b)
{
	Matrix newMatrix;
	newMatrix.setHeight(this->getHeight());
	newMatrix.setWidth(this->getWidth());

	newMatrix.allocate(newMatrix.getHeight(), newMatrix.getWidth());

	for(int i = 0; i < this->getHeight(); i++)
	{
		for(int j = 0; j < this->getWidth(); j++)
			newMatrix.data[i][j] = (this->data[i][j] * b);
	}

	return newMatrix;
}


So, it returns the newMatrix..

Back to the original code:
 
newMatrix = mMatrix * scalar;


Next, it should pass the returned value to the equals overload. Here's that function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Matrix&	Matrix::operator=(Matrix& b)
{
	if (getAllocated())
		this->deallocate();

	this->allocate(b.getHeight(), b.getWidth());

	this->setWidth(b.getWidth());
	this->setHeight(b.getHeight());

	for (int i = 0; i < this->getHeight(); i++)
	{
		for (int j = 0; j < this->getWidth(); j++)
			this->data[i][j] = b.data[i][j];
	}

	return *this;
}


While I'm debugging, once I hit my equals overloaded code, [b], (the passed value) is a bad pointer.. Therefore, the returned value from my Matrix * Scalar overloaded operator is either not returning my Matrix correctly, or there is a problem passing the returned value to the second overloaded operator..

Any suggestions? Thanks in advance :)
Oh wow, I was returning a pointer to the Matrix, not the Matrix itself, getting the right thing now.. I guess I was completely over thinking it..

I'll post a solution in case anyone else is having this problem.. :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Matrix& Matrix::operator*(double b)
{
	Matrix newMatrix;
	newMatrix.setHeight(this->getHeight());
	newMatrix.setWidth(this->getWidth());

	newMatrix.allocate(newMatrix.getHeight(), newMatrix.getWidth());

	for(int i = 0; i < this->getHeight(); i++)
	{
		for(int j = 0; j < this->getWidth(); j++)
			newMatrix.data[i][j] = (this->data[i][j] * b);
	}

	return newMatrix;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Matrix&	Matrix::operator=(Matrix& b)
{
	if (getAllocated())
		this->deallocate();

	this->allocate(b.getHeight(), b.getWidth());

	this->setWidth(b.getWidth());
	this->setHeight(b.getHeight());

	for (int i = 0; i < this->getHeight(); i++)
	{
		for (int j = 0; j < this->getWidth(); j++)
			this->data[i][j] = b.data[i][j];
	}

	return *this;
}
Aaugh! You're making a Matrix class?
What thing have you done to deserve this horrible fate?!
ECE 264 @ University of Massachusetts: Dartmouth.. lmfao I got it all working though :D
Topic archived. No new replies allowed.