• Advertisement
Sign in to follow this  

C++ - Multiple Return Types - Custom ADTs or NULL

This topic is 2770 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Ok so I have built a class to use a linked list with the Custom ADT I have for my program. I have a collection of InventoryBook objects that is added to the list.

I have a function that is supposed to traverse the list, checking the parameter of the function against a member of the object in each node. If the parameter and the member are equal, I wish to return the object in the node. If the parameter is not equal to the member, I wish to return NULL or something of the like, that way I can easily test whether there are any objects with a member that is equal to a certain value.

Is it possible to return multiple types from a function such as this. Right now the function I have written has a return type of "InventoryBook" but this does not work when I try to return NULL, and if the function runs through without finding an object with a matching member to return, my program crashes.

Does anyone know how I can do this, and if it is not possible, what would be the best way to get some kind of functionality like this?

Share this post


Link to post
Share on other sites
Advertisement
Looks like you're returning a copy of the object after locating it in the list. Normally you want to return a pointer (or iterator if you're using std::list) instead. If it's your intention to return the object by value - i.e. a copy, then you need to allow your object to exist in an uninitialised state. You can make the return type std::pair<ObjectType,bool> and in the bool field, set to true if the object was found. If the bool is false, then the object is invalid (probably default constructed where the default constructor sets all fields to zero).
Whenever possible, try to avoid doing the above at all. In 99.9% of cases you should just return the object by pointer or iterator, which allow NULL state.

Quote:
Is it possible to return multiple types from a function such as this. Right now the function I have written has a return type of "InventoryBook" but this does not work when I try to return NULL, and if the function runs through without finding an object with a matching member to return, my program crashes.

How do you intend to represent multiple types in the list? Normally you would have a list of base class pointers and the different types you want to represent in the list all inherit from the base. You can return a pointer or iterator, const or not. however the language doesn't allow runtime determination of return types by value.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement