I'm working on a small side project for a class, but I am in a bit of a mix-up.
I got to the part of making an inventory where I have the derivative classes "Weapon", "Armor" and "Potion" (review code for better picture) and the base class that would be "Item". At least that was my original plan.
However, I wanted "Item" to be a class that could hold information of any item, be it a weapon, armor or potion, so that it would make an easy inventory on the main function (The inventory would then simply be an array of "Item" objects).
The following is my code, please read it and follow up on what I have to say. You could call it a "reverse-inheritance" or something.
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
//Isn't my actual program, but wrote this to give a picture of the situation
#include <iostream>
#include <string>
using namespace std; //Yes. I went there.
//-----------------------------------------------------------------
//-----------------------------------------------------------------
class Weapon
{
protected:
int attack;
public:
Weapon(){}
//Constructors,Get/Set, etc...
};
//-----------------------------------------------------------------
//-----------------------------------------------------------------
class Armor
{
protected:
int defense;
public:
Armor(){}
//Constructors,Get/Set, etc...
};
//-----------------------------------------------------------------
//-----------------------------------------------------------------
class Potion
{
protected:
int potHeal;
public:
Potion(){}
//Constructors,Get/Set, etc...
};
//-----------------------------------------------------------------
//-----------------------------------------------------------------
//Item class inherits from all the other classes, instead of the other way around
class Item:public Weapon, public Armor, public Potion
{
protected:
string itemName;
string itemType;
public:
Item(){}
//Constructors,Get/Set, etc...
};
int main()
{
const int bagSize=25;
Item inventory[bagSize];
}
|
The problem is, since "Item" inherits "Weapon", "Armor" and "Potion", it would have many unused variables. Suppose I wanted to make an item that is a weapon, for example, I would set something like the following:
1 2 3
|
inventory[0].setItemName("Iron Sword");
inventory[0].setItemType("Weapon");
inventory[0].setAttack(50);
|
But the weapon would have a variable of "defense" and "potHeal", which to me seems a bit messy, even if they are not used. Is there a better way of making my inventory? I just couldn't see it when I had "Item" as the base class.
Edited to resemble my program more, I have them as protected, not private.