In C++ specifically, but also generally as an OO design principle, is there anything wrong with doing the following? Is it done in practice? If it shows a clear design flaw, what is a good alternative? Are there any advantages?
class Property {};
class CompositeProperty : public Property
{
...
private:
std::vector<Property> m_properties;
};
So specifically, can a derived class contain base class objects?
As I bit of background I have seen this used to model/mirror an XML structure but felt the design somewhat went in the face of is-a-is-inheritance and has-a-is-composition relationships for which one usually strives.
There is no flaw in design - in fact, this design is only one step away from the well-known and very useful composite pattern. However, there is a significant flaw in the implementation.
Your CompositeProperty
aggregates instances of Property
, rather than aggregating pointers. This kills the ability to use elements of the CompositeProperty
polymorphically. You need to replace a vector of instances with a vector of pointers (preferably, smart pointers) in order to address this issue.
A classic place for the composite pattern is representation of expression trees: you start off with an abstract base, and then add representations for constants, variables, function calls, unary expressions, binary expressions, conditionals, and so on. Expressions such as constants and variables do not reference other expressions, while expressions such as unary expressions, binary expressions, and function calls do. This makes the object graph recursive, letting you represent expressions of arbitrary complexity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With