Multiple inheritance is generally a bad thing, yes. Interfaces are the exception (according to Andre LaMothe). In fact, one of the main benefits of using interfaces is that you can have multiple inheritance without much trouble, which allows for cleaner class heirarchies. For example:
Below is a generic class heirarchy.
Object
Character
Enemy
Player
Item
Shield
Weapon
Ammo
Health
Problem: Some items can be held in an inventory, others are simply collected.
Solution: Make a seperate class for inventory items
Object
Character
Enemy
Player
NormalItem
Shield
Food
InventoryItem
Weapon
Ammo
Gem
Problem: Some inventory items can be used at will, others are just there to collect or are automatically used when needed
Solution: Make a seperate class for usable inventory items
Object
Character
Enemy
Player
NormalItem
Shield
Food
InventoryItem
Weapon
UsableInventoryItem
Ammo
Gem
This leaves us with an increasingly complex structure. Eventually, you're going to have an item that belongs in more than one group (needs methods or data from more than one base class).
Here's the same heirarchy using interfaces.
IInventoryItem
IUsableItem
Object
Character
Enemy
Player
Item
Shield : IUsableItem
Food
Weapon : IUsableItem, IInventoryItem
Ammo : IInventoryItem
Gem
Maybe not the best example. I'll try to use something from my actual code (when I get that far).
|