List of items, in c++

You are breaking some concepts here.
You have vector of pointers to parent class, item. You should only use the methods and members in the item class.

This is not proper implementation:

   for(int x=0;x=i-1;x++){
        cout << v[x]->type;
        if(type=="Sword"){
            cout << " Damage: " << v[x].damage;
        } else if(type=="Shield"){
            cout << " Armor: " << v[x].armor;
        } else if(type=="Potion") << v[x].PlusHealth;

    }

Try adding something like this:

class Item
{
  public:
    // A generic function for child classes to print
    //    their specific details.
    virtual void print_details(std::ostream& out) const = 0;
};

class Sword : public Item
{
  public:
    void print_details(std::ostream& out) const
    {
       out << "  Damage: " << damage << "\n";
    }
};

class Shield : public Item
{
  public:
    void print_details(std::ostream& out) const
    {
      out << "  Armor: " << armor << "\n";
    }
};

class Potion : public Item
{
  public:
    void print_details(std::ostream& out) const
    {
      out << "  Health: " << PlusHealth << "\n";
    }
};

//...
for (unsigned int x = 0; x < v.size(); ++x)
{
  cout << "\n"
       << v[x]->type
       << "\n";
  // Get the child to print the specifics.
  v[x]->print_details(cout);
}

The key point is that you can only access item methods and members directly. You can create item methods, that the child classes will need to implement, for specialized behavior. In the above case, printing specific details.

The item base class contains common methods and members for each child. Keep the concept generic and remember that container of items should be treated generically.

Leave a Comment