One important and essential rule I have learnt as a C++ programmer is the preference of Composition over Inheritance (http://en.wikipedia.org/wiki/Composition_over_inheritance).
I totally agree with this rule which mostly makes things much more simple than It would be if we used Inheritance.
I have a problem which should be solved using Composition but I’m really struggling to do so.
Suppose you have a Vendor Machine, and you have two types of products:
- Discrete product – like a snack.
- Fluid product – like a drink.
These two types of products will need to be represented in a class called VendorCell which contains the cell content.
These two products share some identical attributes(dm) as Price, Quantity and so on…BUT also contain some different attributes.
Therefore using Composition here might lead for the following result:
class VendorCell {
private : // default access modifier
int price;
int quantity;
// int firstProductAttributeOnly
// char secondProductAttributeOnly
};
As you can see the commented lines show that for a single VendorCell depending on the product it containing, only one of these two commented lines will be significant and useable (the other one is only relevant for the other type – fluid for example).
Therefore I might have a VendorCell with a snack inside and its secondProductAttributeOnly is not needed.
Is composition (for the VendorCell) is the right solution? is It seems proper to you guys that someone will determine the VendorCell type via a constructor and one DM (the DM dedicated for the other type) will not be used at all (mark it as -1 for example) ?>
Thanks you all!
Your general rule of favoring composition over inheritance is right. The problem here is that you want a container of polymorphic objects, not a giant aggregate class that can hold all possible products. However, because of the slicing problem, you can’t hold polymorphic objects directly, but you need to hold them by (preferably smart) pointer. You can hold them directly by (smart) pointer such as
You simply define your snacks/drinks by deriving from AbstractSnack/AbstractDrink
and then you can insert or extract products like this:
There are also other solutions such as Boost.Any that uses a wrapper class that internally holds a pointer to a polymorphic object. You could also refactor this code by replacing the
typedefwith a separate classVendorMachinethat holds astd::vector< VendorCell >, so that you can get a nicer interface (with money exchange functionality e.g.)