Returning a datatype other than the declared function header datatype

I have designed a class called matrixType that has some overloaded operators (+, -, *, and <<); the arithmetic operator functions of which are overloaded as member functions of the class. As an alert mechanism, I want a message displayed when two matrices of dissimilar sizes are added/subtracted OR when two incompatible matrices are being multiplied. Displaying this error message is not the problem. However, I want a scheme where on detecting two matrices’ incompatibility, the operator function returns the error message (a string datatype) instead of what would be an erroneous result (the expected matrixType object).

In other words, what I may be essentially asking is: Is it possible for a function, say,

1
2
3
4
5
6
matrixType matrixType::operator+(const matrixType& otherMatrix) const
{
      .
      .
      .
}

to return a dataType (like a string) other than the expected matrixType?
Is it possible for a function to return a dataType (like a string) other than the expected matrixType?

Essentially no. There are some ugly workarounds, however, my recommendation is to throw an exception. The caller is responsible for catching the exception.
1
2
  if (err)
    throw std::exception ("error message");

Topic archived. No new replies allowed.