Thank you very much Peter. I feel as though I'm getting closer to my goal, but I'm running into another issue. I made a virtual getAttack member in BaseItem which returns 0. I ran my program, and to my delight it finally compiled and allowed me to get to the screen which prints the attack value. Although, instead of printing weapon.h's attack_ variable, it's simply returning 0. This is because, as you brought up, my data member is being sliced once it's put into the BaseItem list.
This leads to Polymorphism, and what you mentioned about using pointers. (From my findings) it seems the only way to stop the slicing from occurring is through the use of polymorphism. So, I did just that. I turned my list into std::list<BaseItem*> inventory_, and push_backed &weapon. I also changed the iterator to a pointer iterator, and dereferenced when displaying the needed information.
I ran the program in normal mode and got to my inventory display, when the program crashed with a debug error, abort() has been called. I ran it in debug mode and am getting an unhandled exception: std::bad_alloc at memory location blahblah. This is happening at line 11.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
#include <string>
class BaseItem
{
public:
BaseItem();
BaseItem(std::string name, std::string desc, int id, int value, int weight);
// Getters and Setters
std::string getName() { return name_; };
std::string getDesc() { return desc_; };
int getId() { return id_; };
int getValue() { return value_; };
int getWeight() { return weight_; };
virtual int getAttack() { return 0; };
private:
std::string name_;
std::string desc_;
int id_;
int value_;
int weight_;
};
| |
So, now I'm stumped. Upon googling, some are saying there's a stack overflow issue. If that's the case, why did the non-pointer version work? I can print everything in BaseItem, I just can't access weapon's member because of the slicing. But with the pointers, I'm getting memory issues. Do I need to send the instantiated objects to the heap with 'new'? And if so, where do I define 'new'? If not, any idea on what I can try next?
EDIT!!
I've got it. When adding a new weapon to my list, I just needed to create a pointer first, then allocate the object to the heap. Then store the pointer in the list. Now I can access my getAttack member from the derived class while using the BaseItem class' members as well. Thank you so much for the help Peter. To anyone: I'm still curious as to why the non-pointer list still worked, but the pointer list created a memory leak?
1 2 3 4 5
|
void Inventory::addItem(int attack, std::string name, std::string desc, int id, int value, int weight)
{
Weapon* test = new Weapon(attack, name, desc, id, value, weight);
inventory_.push_back(test);
}
| |