MistyD
MistyD

Reputation: 17223

Return type for returning an object or NULL

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.

Upvotes: 2

Views: 343

Answers (4)

Jim Fred
Jim Fred

Reputation: 1126

Consider a static member of class School that is an invalid school - Something like...

class School {
public:
    static const School invalid; 
...
};

Instead of returning null, you can return a reference to the invalid school and, instead of comparing to null, compare to School::invalid.

Optionally, this invalid school could be a subclass of School with methods that do something predictable - like throw and error - without risking referencing a null pointer.

A null, like any other unnamed constant, is ambiguous about the source or intent of its value e.g., 0x00FFFFFF is less informative than Color::White.

Upvotes: 1

Ralph Tandetzky
Ralph Tandetzky

Reputation: 23600

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.

Upvotes: 7

Shamim Hafiz - MSFT
Shamim Hafiz - MSFT

Reputation: 22064

If you want to return NULL, you may consider returning pointer of school type, as opposed to direct type. This way, you can return NULL and be able to determine from caller if the return was NULL.

Upvotes: 4

Andy Prowl
Andy Prowl

Reputation: 126422

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.

Upvotes: 9

Related Questions