Multiple Inheritance
- What if I want to build a tree-farm
- This is a farm with a sawmill.
- It should inherit CanProduce and Produce from the sawmill.
- It should inherit FoodBonus from the farm.
- The syntax is simple
-
class TreeFarmT: public Farm, public Sawmill
- There is a problem however
- Which version of
Type
and which warehouse
will be referenced?
- This is called the Diamond Problem
- Because of this, some langaguaged do not allow multiple inheritance.
- Unfortunately the syntax from above will not compile.
- So the keyword virtual can be added to the inheritance chain.
-
class FarmT: virtual public BonusBuildingT
-
class SawmillT: public virtual ProductionBuildingT
-
class TreeFarmT: public Farm, public Sawmill
- Meyers says for correct behavior that every public inheritance should be virtual.
- But this adds time complexity.
- And space complexity.
- Names are more complex too.
- Sometimes you need base.childa.chldb.FunctionName()
- He says to avoid this type of multiple inheritance whenever possible.
- But use it if you need it.
- But if you use virtual base classes, avoid placing data in the base class.