459,977 Members | 1,589 Online
Need help? Post your question and get tips & solutions from a community of 459,977 IT Pros & Developers. It's quick & easy.

 P: n/a Is there any way to get to the left-hand side of an operator? Consider the following (this is not meant to be perfect code, just an example of the problem): class Matrix { public: int data[1024]; Matrix() {} Matrix(int value) { for (unsigned i = 0; i < sizeof(data)/sizeof(int); i++) data[i] = value; } void add(const Matrix& obj, Matrix* output) { for (unsigned i = 0; i < sizeof(data)/sizeof(int); i++) output->data[i] = data[i] + obj.data[i]; } Matrix operator +(const Matrix& obj) { Matrix temp; // "unnecessary" creation of temp variable for (unsigned i = 0; i < sizeof(data)/sizeof(int); i++) temp.data[i] = data[i] + obj.data[i]; return temp; // "unnecessary" extra copy of output } }; For nice looking syntax you _really_ want to use the operator+ like: matrix3 = matrix1 + matrix2; However, that is some 50% slower than the _much_ uglier: matrix1.add(matrix2, &matrix3); If only there were a way to get to the left-hand argument of the operator+ then it could be fast and easy to use. Consider the following code which is not valid C++ and will not compile for this example: Matrix as M operator+(const Matrix& obj) { for (unsigned i = 0; i < sizeof(data)/sizeof(int); i++) M.data[i] = data[i] + obj.data[i]; } That would be fast and clean to use. Is there any way to accomplish this? Otherwise the situation is just ugly and there is no point in using operator overloading for these types of situations (which really defeats the purpose of operator overloading in the first place). Thanks! Jo Aug 17 '05