I've got a base class, Item, and derived class, Weapon & Shield. Both overload <<.
// item(base) operator overload
ostream& operator<<(ostream& os, const Item& a_item)
{
os << " Item Object - " << endl;
os << " Name: " << a_item.m_name << endl;
os << " Cost: " << a_item.m_cost << endl;
os << " Purpose: " << a_item.m_purpose << endl;
return os;
}
And:
// weapon(derived) operator overload
ostream & operator<<(ostream & os, const Weapon & a_weapon)
{
os << "Weapon - " << endl;
os << " Name: " << a_weapon.m_name << endl;
os << " Cost: " << a_weapon.m_cost << endl;
os << " Purpose: " << a_weapon.m_purpose << endl;
return os;
}
// shield(derived) operator overload
ostream & operator<<(ostream & os, const Shield & a_shield)
{
os << "Shield - " << endl;
os << " Name: " << a_shield.m_name << endl;
os << " Cost: " << a_shield.m_cost << endl;
os << " Purpose: " << a_shield.m_purpose << endl;
return os;
}
Now, I have a vector<Item> inventory
, to which I'm adding a Weapon and a Shield. When I loop through the inventory and cout the item, I get the Item operator rather than the one for that particular item. Here's how I'm calling the cout:
// person(derived) operator overload
ostream& operator<<(ostream& os, const Person& a_person)
{
os << "Person Object - " << endl;
os << " Name: " << a_person.m_name << endl;
os << " Level: " << a_person.m_level << endl;
os << " Hit Points: " << a_person.m_hit_points << endl;
os << " Inventory: " << endl;
for (auto i = 0; i < a_person.m_inventory.size(); i++)
{
os << " " << a_person.m_inventory[i] << endl;
}
return os;
}
My question is why is it calling the operator overload of the base, instead of the derived? Is it possible to tell it to call the one from the derived class?