Reputation: 8971
A function returns a reference on int
int& MyClass::getElement(int position)
{
if (position < _size)
return (_array[position]);
return ([...]) // An Error
}
My first think was to return NULL. But obviously a reference can not be NULL.
What is the right way to return an error in this case?
Upvotes: 4
Views: 2604
Reputation: 311186
The right way is to throw an exception of type std::out_of_range
in case parameter position has no acceptable value.
Upvotes: 3
Reputation: 830
One other thing to think about is that, even if you were returning an 'int' (i.e. not a reference), NULL would be 0 (and so easily confused with a valid int value that is '0').
If you want to stick to this function definition, then throw an exception to signal an error.
int& MyClass::getElement(int position)
{
if (position < _size)
return (_array[position]);
throw std::out_of_range("Invalid size to getElement");
}
Upvotes: 0
Reputation: 254771
Various options, roughly ordered with my preferred options first:
std::out_of_range
std::pair<bool,int&>
or boost::optional<int&>
. This is more useful if you want to return something by value, not reference, so can't return a pointer.Upvotes: 6
Reputation: 21013
If you need to return reference, you have to throw an exception in case of error.
Upvotes: 0