I currently have a method that returns back an object (say school). However sometimes in that method it could return NULL which is an int. What should the return type of such a method be.that I could return any of the two safely. Any suggestions ? I am open to other approaches.
If the type you want to return does not have a natural "null" value, boost::optional seems to be what you're looking for.
However, consider whether not being able to produce a value to return is an error condition or not. If it is, rather than returning a boost::optional (or a null value), consider having your function always return the intended type (whatever it is) and throw an exception when a return value cannot be produced.
You should probably return an std::unique_ptr<school>, if you have a C++11 compiler. If you already have C++14 stuff, then maybe std::optional<school> will work. If you have boost installed and you don't have std::optional, you may consider boost::optional<school>. You should not return a raw pointer, since it's not clear then, who's responsible for deleting the pointer from the function interface.
As Andy noted, it might be an option to throw an exception, if the return value cannot be successfully constructed. This makes sense, if the case doesn't occur frequently and the caller would not typically expect the function to fail.
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