0

As with seemingly everyone else that attempts to self-learn c++ I'm beginning by making an RPG and struggling with the inventory. I have a base Item class of which has three derivative classes Consumable, Weapon, Armor. I understand that when these objects are added to an Item vector, object splicing occurs such that most of the information is lost. The solution is to make a vector of pointers. However, I'm having a hard time finding the correct way to make it work. I think I'm very close...

For example, here is my code for the function that is supposed to return an item from the inventory. My hope is that it can return the item as type derivative class with all of it's information retains so that it can be used:

    bool have = false;
    Item* item_found;

    std::for_each(items_test.begin(), items_test.end(), [&](Item* itm) 
    {
        if (itm->name == "Helmet")
        {
            have = true;
            item_found = itm;
        }
    });

    if (have == false) {
        std::cout << "Item not in inventory." << std::endl;
    }

I think I successfully (since it runs with no errors and the typeid is Item*) return the pointer of the Item in the list with name "Helmet". However, I'm not sure how to then take this pointer to this object of derivative class Armor and get the relevant information to Armor. I'm sure it's simple, but I'm piecing this information together from websites and videos so I have big gaps in my knowledge.

cloudbox
  • 53
  • 5
  • 1
    Does this answer your question? [C++ inheritance downcasting](https://stackoverflow.com/questions/11855018/c-inheritance-downcasting) Basically it's something like `auto armor = dynamic_cast(item_found); if(armor) {/*verified as pointer to Armor, do stuff */ }` – Lukas-T Jun 14 '20 at 19:29
  • 3
    Yes, `dynamic_cast` is the way to go. Also, if you wouldn't mind the suggestion, `std::find_if` would be more natural in your context. `std::find_if(items_test.begin(), items_test.end(), [](const Item* itm) { return itm->name == "Helmet"; });` – jvd Jun 14 '20 at 19:33
  • Thanks to both of you, I got it working today. I see how the find_if function would be more natural, however it kept throwing errors for me when I tried to implement it. I have much to learn :O. – cloudbox Jun 16 '20 at 06:45

0 Answers0