Composition

Every big thing is made up of small-small things. For example, a house is built from walls, ceiling, and doors. Now in terms of C++, we can say that every complex object is built from small or simple object.

This process of creating a complex object from simple and small objects is called composition in C++. In other words, whenever there is “has-a” relationship, then composition comes in to picture. E.g., house has four walls, two doors and one ceiling.

Let us try to understand the concept of composition with the help of an example:

#include <iostream>
using namespace std;
class Wall {
private:
unsigned short m_noOfBricks;
public:
Wall(unsigned short noOfBricks):m_noOfBricks(noOfBricks) {
cout << "Wall object is constructed" << endl;
}
~Wall() {
cout << "Wall object is destructed" << endl;
}
};

class Door {
private:
enum {
WOOD_DOOR_TYPE=0,
MESH_DOOR_TYPE=1,
ALUMINIUM_DOOR_TYPE
};
unsigned short m_typeOfDoor;
unsigned short m_noOfBolts;
public:
Door(unsigned short typeOfDoor, unsigned short noOfBolts):  
m_typeOfDoor(typeOfDoor), m_noOfBolts(noOfBolts) {
cout << "Door object is constructed" << endl;
}
~Door() {
cout << "Door object is destructed" << endl;
}
};

class house {
private:
Door m_door;
Wall m_wall;
public:
house():m_wall(100), m_door(0, 2) {
cout << "house object is constructed" << endl;
}
~house() {
cout << "house object is destructed" << endl;
}
};

Output:
Door object is constructed
Wall object is constructed
house object is constructed
house object is destructed
Wall object is destructed
Door object is destructed

  • As part of creating the house object, creation of object depends on order they are added in the class and not in the order they are initialized in the initializer List.

  • In this case, house class is composed of Door and Wall member. So first Door object is constructed, then Wall and eventually house.

  • Order of Destructor is reverse.

  • With the help of composition, it is easier to understand the code since complex object is prepared from simple or smaller objects. We can say that bigger class delegates the task to its smaller objects.

  • With the help of composition, it is easier to do modification. E.g. if we want to do any amendment in any class, programmer can do the amendment and perform some minor updates in the bigger class E.g. house in this example and that’s it.

Related posts