0

I have a function, which looks something like this:

ClassA& ClassB::Check(int x){
    //some calculations in a loop, if a condition is met, a reference to a ClassA object is given
}

I'm getting the "control reaches end of non-void function" error. As far as I understand, this is because, the function wont always return something, am I right?

The function is getting the mouse coordinates and checking witch objects was selected. If something was selected, then do stuff, otherwise do nothing.

What would be the best option to solve this? Should I create and return an object with some kind of flag to check against?

2 Answers 2

8

You should not be returning a reference in this case but rather a pointer. In case there is no object to return, you should return 0. Another option to consider is to stick with returning a reference, but if you cannot for some reason, throw an exception.

4
  • In the pointer case, you might want to return NULL rather than 0, since it's more descriptive (though they're equivalent in this case).
    – Cyanfish
    Commented Oct 8, 2013 at 15:00
  • 1
    Hm, I guess the case where nothing was selected is not so "exceptional" that throwing an exception is the right thing to do here.
    – Doc Brown
    Commented Oct 8, 2013 at 15:22
  • @Cyanfish - if you have access to C++11 you should be returning nullptr which has better type safety. Actually in this particular case you might even want to return a std::unique_ptr that potentially contains a nullptr, depending on the ownership situation of the return value. Commented Oct 8, 2013 at 15:50
  • Maybe there's a default object which can be returned, aka the null-object-pattern... Commented Jan 1, 2016 at 22:17
2

Following the SOLID principles (especially the "S" = single responsibility), you may consider to split this up into 2 functions:

  • one doing the check and returning a bool to signal if the check was successful or not, and
  • one to request the reference to the classA object.

Currently, yur current function has two responsibilities (checking and returning a related object).

Or you rename your function to GetSelectedObject, in which case the first part of @JoelFan's answer is fine. This changes the point of view about the responsibility of that function.

1
  • Thanks for your reply, will keep those principles in mind Commented Oct 8, 2013 at 15:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.