Item class is a base abstract class. Both Weapon and Armor are derived class. As far as i can remember the above is legal, but when the code goes like this
/*-------- Item Class --------*/
Item(string tname, int tprice, int tuseLevel);
virtual char getType();
virtual int getDamage()=0;
virtual bool isTwoHanded()=0;
virtual int getProtection()=0;
/*-------- Weapon(Item) Class --------*/
class Weapon : public Item
Weapon(string tname, int tprice, int tuseLevel ,int damage, bool twohands);
/*-------- Armor(Item) Class --------*/
class Armor : public Item
Armor(string tname, int tprice, int tuseLevel ,int tprotection);
MS VS compiler produces :
Item *equipedWeapon = new Weapon("Wooden Stick", 0, 1, 5, false);
Item *equipedArmor = new Armor("Shirt", 0, 1, 2);
error C2259: 'Weapon' : cannot instantiate abstract class
error C2259: 'Armor' : cannot instantiate abstract class
Following the error code i came up to this which doesn't explain why i have to define the functions of Armor also in Weapon class and vice versa.
You need to override all pure methods (=0) if you want to instantiate those.
IMO, one idea to design the whole thing would be not to have different subclasses, but instead have the Item class contain all attributes in a map, e.g
If you want to use inheritance and polymorphism, then perhaps don't make anything pure abstract, but instead make the base class provide a default implementation (e.g by default an Item does 0 damage, offers 0 protection, is not two-handed etc), which subclasses may override if needed (e.g Weapon overrides getDamage, but doesn't add any protection and doesn't override getProtection).
std::map<std::string, int> data;
int get(const std::string& attribute) const;
Item equipedWeapon("Wooden Stick", weapon_init_data ...);
int weaponDamage = equipedWeapon.get("damage"); //etc
If you want to make sure Item is not instantiated, it is enough to make only the destructor pure virtual. Making other methods pure virtual means that derived classes are expected to override all of those.
I can't see the point of overriding (for example) the getProtection() function in Weapon class.
Originally Posted by anon
It can lead to chaos for deep inheritance.
Anyway, thank you.
Perhaps you replied before I had finished editing.
If it doesn't make sense to force derived classes to override those methods, then don't mark them pure virtual.
It really doesn't make sense to me right now (more than two years away from oop), because i can't see reuseability.