Composition - RJAE5/2143-OOP GitHub Wiki

Composition (HAS-A)

Using a user-defined type (typically a class) within the definition of another class is known as composition. This is most often needed when trying to model a multifaceted generalized thing that has properties that cannot be described by a single primitive type. When determining to use composition over inheritance, it is simplest to ask if the bigger item HAS-A smaller item, or if the bigger item IS-A subset of a broader range of items. If the HAS-A phrase sounds more sensible, then the relationship will be composition.

Example

In this example, a phone HAS-A screen associated with it, so it is a compositional relationship.

class Screen
{
    int height;
    int width;
    char model;
    string serial;
public:
    // Methods go here
};

class Phone
{
    int cost;
    char model;
    string serial;
    Screen screen;
public:
    // Methods go here
};

Important Notes

  • Composition is more widely used than inheritance
  • Determining composition over inheritance is not always straight forward, i.e. "A compiler HAS/IS -A program"

Sources:

  1. https://www.geeksforgeeks.org/object-composition-delegation-in-c-with-examples/
  2. https://www.scaler.com/topics/composition-in-cpp/