Reputation: 2456
Coding an inventory that can contain 6 items would probably look something like this:
class Inventory {
private:
Item[6] m_items;
};
Now on the other hand an item would look like this:
class Item {
private:
Inventory* m_parent;
};
However, obviously both classes cannot know each other.
One solution would be a common base class, but the two classes don't have anything in common and it would lead into more problems, such as: I wouldn't be able to call m_parent->addItem(this);
from Item
's constructor.
Upvotes: 1
Views: 94
Reputation: 14392
I agree with Ben's answer, but I want to extend that when the inventory needs to know about changes from the item or if the item needs some extra information from the inventory, this should be handled by callbacks. Callbacks can be implemented in several ways (function pointer, interface, std::function, signal/slot,...), but the main thing is: the item doesn't know about the inventory.
example:
class CallbackInterface {
public:
virtual void itemChanged() = 0;
};
class Item {
public:
Item(CallbackInterface* callback): m_callback(callback) { }
private:
CallbackInterface* m_callback;
};
class Inventory: public CallbackInterface {
private:
Item[6] m_items;
virtual void itemChanged() {
std::cout << "item has changed";
}
};
Upvotes: 0
Reputation: 71535
An item is logically complete in and of itself. Items would be worth modelling in a system that didn't have a concept of inventory at all. An item may not even be in an inventory. It may even theoretically be in more than one inventory, depending on what kinds of items and inventories you're modelling.
An inventory, on the other hand, exists solely for the purpose of containing items. It may not have any items in it at the moment, but that in itself is a core property of the inventory.
The above considerations lead me to conclude that an inventory should know the concept of items and about the particular items it holds. While items should be implemented to be completely oblivious not just to which inventory(ies) they are in, but to the concept of inventories.
Upvotes: 5