Home C++ OOP inventory and item class
Reply: 1

C++ OOP inventory and item class

scoobz1234 Published in 2018-02-12 23:24:54Z

creating Inventory class as well as item class... working on inventory "removing" item from inventory.

#include "Inventory.h"
#include <iostream>

void Inventory::PrintInventory() {
    for (auto i = items.begin(); i != items.end(); i++) {
        std::cout << i->name << " " << i->numItem << std::endl;

void Inventory::ReceiveItem(Item item) {

Item Inventory::TakeItem(int num) {
    items.erase(items.begin() + num);
    auto item = std::find(items.begin(), items.end(), num);
    //issue is here
    //my teacher said to set it up as Item Inventory that takes in an int.
    return item;

//this is in the actor class...

void Actor::GiveItem(Actor* actor, Item item) {
    int num = item.numItem;

question is... im not sure what to do in the Item Inventory function of the Inventory class, it's supposed to return something, but im not sure why.. teacher is unreachable. and if it is supposed to return an Item object, i need to get Item object from the integer value. the Item objects class has a char* name; and int numItem;

Justin Randall
Justin Randall Reply to 2018-02-13 03:50:55Z

It is supposed to return an Item object, I need to get Item object from the integer value.

Okay so you're pretty close here. From your description it sounds like Item is defined as

struct Item
    std::string name;
    int numItem;  ///< search for this value

And your items is an STL container of Item, we'll use std::vector<Item> items;.

If you must return an Item object then you should declare a default Item to return on error. If you successfully find a match for Item::numItem then you will populate your default Item with these values. Finally, if you did find an item to take, you will erase it for inventory housekeeping. Do not erase the Item before you find it for obvious reasons!

Item TakeItem(int num)
    Item localItem;
    for (auto it = items.begin(); it != items.end();) {
        // if we find a match set local item and then
        // remove the item from inventory
        // and break out of loop since we are done
        if ((*it).numItem == num) {
            localItem = *it;
            it = items.erase(it);
            break; // found and removed from inventory!
        } else {
    return localItem;

It's a little bit awkward to return a default-constructed Item in the event that there were not any matches for num found, but if you want to detect that case you could always do something like initialize it to "bogus" values that you know can't be in your inventory.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.304683 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO