Composition C++ | Sololearn: Learn to code for FREE!


Composition C++

Am I right in thinking composition is when a second object uses a copy of the first objects values in the constructor rather than the data that the constructor stored in the private variables of the first object? In other words, you can't use composition without a constructor. The lesson on composition uses this example, but as they are private variables I got a bit confused how the second object could see them.

6/5/2019 4:17:20 PM


4 Answers

New Answer


Yes right, it is easy to describe it in words, but real use is not that simple. A simple example would be.. Suppose you have a 3d open world game populated by many different characters: The game engine could have a Pawn class representing every entity, but since we have several types of characters and we may add some later we choose to use components to build our characters. The Pawn class will have: -scene component -3d model comp -inventory comp -..... -controller component (different AI ) think for example the last component: AI.. With that design you don't have to make a class for every kind of AI You simply attack an AI_Archer or AI_Warrior or AI_Boss, AI_NPC... to your Pawn making it a warrior,archer... And it behaves accordingly without have to redefine the entire class. So you build components and attack them like Legos. This way you can build a lot of different characters easily just combining those components.


Composition is the technique to add functionalities to your class using different classes, and not by implementing those functionalities inside your class. This allows you to design extremely flexible systems. It is often preferred over inheritance. Suppose you have a generic class , isn't it awesome to add functionalities just adding some objects of classes designed for one functionality only? This way an instance of your class doesn't have to have all the functionalities, but only what needed.


Thank you for the reply. I will have to think up some examples to get my head around it better 🙂


That is a good way of thinking of it and also how all these tools in programming are used in real life scenarios. I have just reached the topic of constructors/destructors and composition in the book im learning from; I am starting to link everything I have learnt about classes together now, I feel I am unlocking something very exciting. 🙂