Hello all,

I am trying to build an electrical simulator in C++. This will involve matrix manipulations to a great deal and so I created in my own class Matrix. I have overloaded all operators such as *, +, - to make the final numerical integration easier to read. The code Matrix.h is attached.

I would like this C++ code to run superfast since I might have to run it in real-time. So am looking for ways to simplify the code. An example for adding two matrices is as follows:

Code:
Matrix operator+(const Matrix &mat2) const {
	Matrix temp(rows, columns);

	dimension_check(*this);
	dimension_check(mat2);

// Checking for compatibility.
	if ((rows!=mat2.rows)||(columns!=mat2.columns)) {
		std::cout << "Matrices are not compatible.\n";
		exit(1);
	}

// Performing addition.
	for (int x=0;x<rows;x++) {
		for (int y=0;y<columns;y++) {
			temp.mat_var[x][y]=mat_var[x][y]+mat2.mat_var[x][y];
		}
	}

	return temp;
}
I posted this code on Cboard a couple of years ago when I was thinking about this and people suggested a few things to speed up execution:
1. Passing objects as reference (const reference if necessary).
2. Dynamic allocation of arrays (in Matrix.h).

One major problem:
The result in the above function is the temporary object temp. I am creating this in the function and it is returned containing the sum of the arrays. But if this is a part of a simulator running maybe a million times with a for loop, the object will be created and destroyed a million times. For an object addition statement like this:
Code:
a=b+c;
where a,b,c are objects. Is there any way the result "a" can be passed to the overloaded operator function as a reference?

Another way to do this is simply define a function:
Code:
matrix_addition(a,b,c);
where all of them will be passed as references. But the readability of the code will decrease.

Thanks in advance.