Here's my code:
Composer& Database::GetComposer (string in_last_name)
{
for (int i = 0; i < next_slot_; i++)
{
if (composers_[i].last_name() == in_last_name)
return composers_[i];
}
}
The idea is to iterate over an array of Composer objects and return a reference to the object whose last_name field matches "in_last_name." I understand what the warning is telling me, namely that it's possible that the function won't return anything (if, say, the user provides an invalid last name). My question is, how can I avoid this? I tried adding "return 0" and "return NULL" after the for loop and it wouldn't compile. Should this method throw an exception if it finds nothing?
Your function is declared to return a Composer&
, that is, a reference to a Composer
. If your function fails to return a suitable reference, and the caller tries to use the return value for something, undefined behaviour will result.
If your function may legitimately fail to find what it's looking for, you may want to change the return type to a pointer instead of a reference. That would give you the option to return NULL
:
Composer* Database::GetComposer (string in_last_name)
{
for (int i = 0; i < next_slot_; i++)
{
if (composers_[i].last_name() == in_last_name)
return &composers_[i];
}
return NULL;
}
Alternatively, you could throw an exception when your function fails to find the target.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With