Nested class question

I was once making a text based game to take a pause from learning.
I made a class Character to represent the player, the class included methods (Attack,Defend,getHP,setHP,etc.).
I made another class called Item to represent a single Item and it's stats (BonusHP,BonusAttack, etc.).
I wanted the player to have an inventory so basically I did something like this

1
2
3
4
5
6
7
8
class Player
{
public:
//The methods
private:
Item inventory[20];
//variables
};


I nested the Item class into the Player class and made it an array to represent the inventory slots. The problem was, I needed to display the Items durability or description, name...
But because the nested Class was private I couldn't access the method this way
1
2
Player one;
one.inventory[0].getDurability();

So I thought that I make some methods in the Player class to access these variables but it started to grow bigger and I would have to copy every method from Item to Player.
I even added a method into the Player class that returns a copy of inventory[i] and that copy I gave to a pointer that could access the object for information... But it had it's problems and I had to remove it... So in the end I made the
 
Item inventory[20];

public, that way I could access it. Is it right that way ? It feels weird to do it that way. Is there any better way ?

Last edited on
This works even if Item is private:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Player
{
private:
	class Item
	{
	public:
		int getDurability() const { return 10; }
	};
public:
	const Item& getItem(int i) const { return inventory[i]; }
private:
	Item inventory[20];

};

int main()
{
	Player one;
	one.getItem(0).getDurability();
}

But question is why you want to make Item private if it's going to be used from elsewhere. I don't see much benefit making it a nested class at all. It could just as well be a normal class.
Last edited on
Topic archived. No new replies allowed.