Ad Code

Composition or Aggregation ?

To some extent, we can say that coupling is determined by Aggregation because Aggregation reduces the number of objects that must be visible at the level of enclosing objects and it may lead to undesirable tighter coupling among objects. Whereas, cohesion is a measure of how strongly-related or focused the responsibilities of a single module are. Composition is again specialize form of Aggregation. In case of Composition relation, the relating objects cannot live independent of each other. For example, a class contains students. A student cannot exist without a class. There exists composition between class and students. In cohesion, modules can exist independently so we cannot conclude that cohesion is dependent upon composition.



As we know that composition is used for objects that have a has-a relationship. For example, A personal computer has-a CPU, a motherboard, and other components.

Composition can be done by using classes as member variables in other complex classes. Below is the example code for understanding composition relationship.

class PersonalComputer
{
private:
   CPU m_cCPU;        // object of class CPU
   Motherboard m_cMotherboard;   // object of class Motherboard
   RAM m_cRAM;    // object of class RAM
};

In an aggregation, we also add other subclasses to our complex aggregate class as member variables. However, these member variables are typically either references or pointers that are used to point at objects that have been created outside the scope of the class. Consequently, an aggregate class usually either takes the objects it is going to point to as constructor parameters, or it begins empty and the subobjects are added later via access functions or operators.

Let’s take a look at our Teacher and Department example:

class Teacher
{
private:
    string m_strName;
public:
    Teacher(string strName)
        : m_strName(strName)
    {
    }
 
    string GetName() { return m_strName; }
};
 
class Department
{
private:
    Teacher *m_pcTeacher; // This dept holds only one teacher
 
public:
    Department(Teacher *pcTeacher=NULL)
        : m_pcTeacher(pcTeacher)
    {
    }
};
Reactions

Post a Comment

0 Comments