Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What, if anything, is wrong with a child class containing a parent class object in C++?

Tags:

c++

oop

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.

like image 831
Jake_Howard Avatar asked Dec 08 '22 22:12

Jake_Howard


1 Answers

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.

like image 152
Sergey Kalinichenko Avatar answered May 12 '23 13:05

Sergey Kalinichenko