Reputation: 1121
Hi I am now writing a program handling matrix manipulation and I am struggling on the error handling issue in a member function.
Given a function
double & MATRIX::elements(int i, int j) const;
it is the function that can return a reference back, so the function can be a lvalue, e.g.
object.elements(1,2)= 2; // I can change the value matrix element (1,2) to be 2
I assume that some people may enter the index of the matrix wrongly (i.e.invalid value of i and j) that the element (i,j) does not exist. Therefore, I write an if-else statement, however, I wonder what should I return when invalid values of i and j are found?? Can I prevent the function from returning anything so situations like
object.elements(100,100000)= 2; // where the matrix size is only 3x3
won' t happen??
P.S. I store the matrix elements in a dynamic array when I create the object
Upvotes: 1
Views: 67
Reputation: 145239
There are three practical possibilities:
assert
the precondition, and rely on testing to root out all invalid calls, orIn the old days one also included schemes such as calling a user-provided error function, but really what could it do except terminate or throw an exception.
The third possibility, returning a known-as-such error value, may appear unsuitable for your present predicament, which ideally would return a double&
which would be immediately used. But in general it's a valid option. For example, it can be implemented as a Boost optional
.
In passing, some general advice.
For the given code,
double & MATRIX::elements(int i, int j) const;
usually a const
method does not provide read/write access, it defeats the purpose. However there are exceptions, such as for a proxy object. But on the third and gripping hand, the above code is not for such objects.
Also, consider reserving ALL UPPERCASE identifiers for macros. That way you can avoid some name collisions. Remember that macros don't respect scopes, and since a great many people use all uppercase identifiers for macros, while few do otherwise, the chance of a collision, resulting in undesirable text substitution, is greater with uppercase used for ordinary identifiers.
Upvotes: 2