returning error

Hi, my question is how to return an error in a function that is supposed to return an object.

I have a class declared as:
1
2
3
4
class MyClass
{
...
}


I also have an array of objects of MyClass type, and a function that returns an object from this array based on the position:
1
2
3
4
MyClass getByPosition(unsigned int pos)
{
  return array[pos]
}


But I want this function to indicate to the main error if the position "pos" is not correct (higher than maximum value). Is it possible to return "void"? Perhaps I could return a pair (an error code + the object itself)? Which is the ideal solution for this kind of functions?
maybe you could use a try catch in that function kind of:

you find an error
throw -1

and in the main function you
catch the error
You cannot do this: return void;, however you can return nothing via a function whose return type is void.

However, I'd recommend an integral value, that is zero when pos is in bounds, or a non-zero value that would indicate how many spaces out of bounds pos is.

EDIT: you could return a class that has the error code + the object itself.

-Albatross
Last edited on
Is your function getByPosition() going to be doing any more than what is shown? If not, just eliminate the function call entirely, and handle bounds checking prior to accessing the element in your array. The function call as provided is unnecessary.
Yes, JRaskell, my function is going to do something more, so I really need it (something about singletons...).

Can I write:
1
2
3
4
5
6
7
MyClass getByPosition(...)
{
   ...
   if (...)
      return -1;
   ...
}

returning -1 even if I have to return a MyClass object?

In that case, what kind of values could I return? Only -1 or any integer?

And, how can I check in the main program if I have returned -1 instead of a MyClass object?

If a better solution is returning a pair, how can I do that?
you could do it this way
let's say you need to get an error if a number is biger then 5

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void Function(int a){
                     if(a>5)
                     throw -1;
                     .
                     .
                     .
                     .
           }

int main(){
try{}
.
.
.
catch(int b){
             if(b==-1)
             cout << "a is biger than 5";
}


in that way you can "throw" a number whenever you need an error, you catch it in the int b, and you can give the info what the error is...

hope it helps
Using throw is a potential solution, and not a bad one either. You'll just have to remember to catch it in your main. If you forget, it could lead to some bugz...

But throw isn't a bad option. Just make sure that your function is the only thing in the "try" block.

http://cplusplus.com/doc/tutorial/exceptions/
Just in case.

-Albatross
closed account (jwC5fSEw)
This is pretty much exactly what exceptions are for. I think throw is the best option here.
Topic archived. No new replies allowed.