//item class
class item
{
public:
//stuff
item(int valueT, std::string nameT);//constructor
std::string getName(){return name;}
private:
std::string name;
int value;
};
//function in question
item function()
{
std::cout << "welcome bla bla bla " << std::endl;
vector <item> warehouse;
warehouse.push_back(item(4,"couch"));
warehouse.push_back(item(6,"tv"));
warehouse.push_back(item(10,"wardrobe")); //create some objects of item class
int money = 3, cnum; //oh noes, we don't have enough monies for anything :(
char opt;
std::cout << "Here are our current items!" << std::endl;
for(int i = 0; i < warehouse.size();i++)
{
std::cout << i << ": " << warehouse[i].getName() << std::endl;
}
}
std::cout << "To choose an item simply enter it's correspondent number:" <<std::endl;
std::cin >> cnum;
std::cout << "Are you sure you wish to buy " << warehouse[cnum].getName() << "? y/n\n " ;
std::cin >> opt;
//HERE IS THE MAIN PART
if(opt == 'y'){
return warehouse[cnum];
}else{
//std::cout << "Okay, cya! " << std::endl;
//I don't want to return anything!
}
The logic is fine, but my compiler doesn't seem to like it that I don't return anything. And it crashes if the user doesn't buy anything. How can I solve this without having to remake the function?
Edit: my program crashes if the first condition is not met, meaning, it crashes if my function doesn't return the class type.
Edit 2: I also realized I could construct a blank item and simply return that item, however I want to print a list of items later in my main function and I don't want to have a blank item among that list.
There are a few ways of doing it. First, you could return a 'dummy' object, i.e. an item that can be seen as being invalid in some way. Second, you could return a pointer to an item, and either return a new allocated item or a nullptr.
The option that I would go for, but you probably won't, is if you use the Boost libraries ( http://www.boost.org ) then you could use boost::optional to signify that you have an optional return type. Of course, you could always roll your own 'optional' class, if you knew how, and use that.
:( I don't think I know anything about the options you're giving me, I might end up just making the function void and simply adding the item to a vector or not.