Add any object in Vector

I have a class structure which is Armor->Weapon->Item . So The Weapon inherits Item and Armor inherits weapon. I also have an inventory class which is std::vector<Item*> playerInventory; . What I am trying to do it make it where the vector can accept any object. My Item class has only a protected value of: itemName so all the classes inherit it. With my current vector, only the name will be passed on. I tried making a template such as this in the Inventory class:

template<class T>
bool Inventory::addItem(T a){
if (playerInventory.size() <= inventorySize) {
playerInventorys.push_back(a);
return true;
} else
return false;
}

but the vector only takes in Item objects. How would I make it so it takes in any object.
bool inventory::addItem(Item *a)


Your members have weird names.
Last edited on
Sorry I didn't explain it very well. I know I can do this but if I were to do this, then I cannot access the functions that's in the weapons or armor classes.
I want something like:

Weapon one = new Weapon();
Armor two = new Armor();
vector<accept any object> inventory;
addItem(one);
addItem(two);

Ok now, If I were to look through the vector, I can access the functions which are in one and two. If I were to do the above code you posted, I could only use the returnName() function since that is what the item class only has. So If I were to try to access returnArmorType();, it would not work.
Last edited on
> then I cannot access the functions that's in the weapons or armor classes.
Because as far as you know, they are just `items'.
You could simply cast to the appropriate type (¿how would you know which type?).
http://cplusplus.com/doc/tutorial/typecasting/ (dynamic_cast)

As alternatives, provide more functionality in the base class, or use another bag.
Last edited on
Topic archived. No new replies allowed.