You are on page 1of 71

ASSOCIATION,COMPOSIT

ION AND AGGREGATION

1
2
OVER ALL ILLUSTRATION

3
 In Object-oriented programming, one object is related to other to use functionality and
service provided by that object. This relationship between two objects is known as
the association.
 Both Composition and Aggregation are the form of association between two objects,
but there is a subtle difference between composition and aggregation, which is also
reflected by their UML notation.
 The composition is stronger than Aggregation.  In Short, a relationship between two
objects is referred as an association, and an association is known as composition when
one object owns other while an association is known as aggregation when one
object uses another object.
4
ASSOCIATION
 Association is relation between two separate classes which
establishes through their Objects.
 Association can be one-to-one, one-to-many, many-to-one, many-to-
many. In Object-Oriented programming, an Object communicates to
other Object to use functionality and services provided by that
object. 
 Composition and Aggregation are the two forms of association.
 To qualify as an association, an object and another object must
have the following relationship:
5
1.The associated object (member) is otherwise unrelated to the object

(class).

2.The associated object (member) can belong to more than one object

(class) at a time.

3.The associated object (member) does not have its existence managed by

the object (class).

4.The associated object (member) may or may not know about the

existence of the object (class)


6
Multiple students can associate with a single Department and single student can
associate with multiple Departments, but there is no ownership between the
objects and both have their own lifecycle.

7
REFLEXIVE ASSOCIATION

Sometimes objects may have a relationship with other objects

of the same type. This is called a reflexive association. A good

example of a reflexive association is the relationship between a

university course and its prerequisites.

8
Example 1

9
// C++ program to illustrate the
// concept of Association
// class bank

class Bank
{
private String name;

// bank name
Bank(String name)
{
this.name = name;
}

public String getBankName()


{
return this.name;
}
}

10
// employee class
class Employee
{
private String name;

// employee name
Employee(String name)
{
this.name = name;
}

public String getEmployeeName()


{
return this.name;
}
} 11
// Association between both the
// classes in main method
class Association
{
public static void main (String[] args)
{
Bank bank = new Bank("Axis");
Employee emp = new Employee("Neha");

System.out.println(emp.getEmployeeName() +
" is employee of " + bank.getBankName());
}
}

OUTPUT:
Neha is employee of Axis
12
Example 2

13
#include <iostream>
#include <string>
#include <vector>
 
// Since these classes have a circular dependency, we're going to forward declare Doctor
class Doctor;
 
class Patient
{
private:
std::string m_name;
std::vector<Doctor *> m_doctor; // so that we can use it here
 
// We're going to make addDoctor private because we don't want the public to use it.
// They should use Doctor::addPatient() instead, which is publicly exposed
// We'll define this function after we define what a Doctor is
// Since we need Doctor to be defined in order to actually use anything from it
void addDoctor(Doctor *doc);
14
public:
Patient(std::string name)
: m_name(name)
{
}
 
// We'll implement this function below Doctor since we need Doctor to be defined at that point
friend std::ostream& operator<<(std::ostream &out, const Patient &pat);
 
std::string getName() const { return m_name; }
 
// We're friending Doctor so that class can access the private addDoctor() function
// (Note: in normal circumstances, we'd just friend that one function, but we can't
// because Doctor is forward declared)
friend class Doctor;
};
 
class Doctor
{
private:
std::string m_name;
std::vector<Patient *> m_patient;
 
15
public:
Doctor(std::string name):
m_name(name)
{
}
 
void addPatient(Patient *pat)
{
// Our doctor will add this patient
m_patient.push_back(pat);
// and the patient will also add this doctor
pat->addDoctor(this);
}
 
  16
friend std::ostream& operator<<(std::ostream &out, const
Doctor &doc)
{
unsigned int length = doc.m_patient.size();
if (length == 0)
{
out << doc.m_name << " has no patients right now";
return out;
}
 
out << doc.m_name << " is seeing patients: ";
for (unsigned int count = 0; count < length; ++count)
out << doc.m_patient[count]->getName() << ' ';
 
return out;
}
std::string getName() const { return m_name; }
};

 
17
void Patient::addDoctor(Doctor *doc)
{
m_doctor.push_back(doc);
}
 
std::ostream& operator<<(std::ostream &out, const Patient &pat)
{
unsigned int length = pat.m_doctor.size();
if (length == 0)
{
out << pat.getName() << " has no doctors right now";
return out;
}
 
out << pat.m_name << " is seeing doctors: ";
for (unsigned int count = 0; count < length; ++count)
out << pat.m_doctor[count]->getName() << ' ';
 
return out;
}

18
int main()
{
// Create a Patient outside the scope of the Doctor
Patient *p1 = new Patient("Dave");
Patient *p2 = new Patient("Frank");
Patient *p3 = new Patient("Betsy");
 
Doctor *d1 = new Doctor("James");
Doctor *d2 = new Doctor("Scott");
 
d1->addPatient(p1);
 
d2->addPatient(p1);
d2->addPatient(p3);
 
std::cout << *d1 << '\n';
std::cout << *d2 << '\n';
std::cout << *p1 << '\n';
std::cout << *p2 << '\n';
std::cout << *p3 << '\n';
19
delete p1;
delete p2;
delete p3;
delete d1;
delete d2;
 
return 0;
}

This prints:

James is seeing patients: Dave


Scott is seeing patients: Dave Betsy
Dave is seeing doctors: James Scott
Frank has no doctors right now
Betsy is seeing doctors: Scott

20
Aggregation
It is a special form of Association where:

 It represents Has-A relationship.

 It is a unidirectional association i.e. a one way relationship. For example, department

can have students but vice versa is not possible and thus unidirectional in nature.

 In Aggregation, both the entries can survive individually which means ending one

entity will not effect the other entity

21
 To qualify as an aggregation, a whole object and its parts must have the following

relationship:

1.The part (member) is part of the object (class)

2.The part (member) can belong to more than one object (class) at a time

3.The part (member) does not have its existence managed by the object (class)

4.The part (member) does not know about the existence of the object (class)

22
Aggregation C++ Syntax
• There are two basic ways in which associations and aggregations are
implemented
1.Objects contain Objects
2.Objects contain pointers to Objects
• The first approach is used to create fixed aggregations (objects inside
objects)
• The second is used to create variable aggregations to make programs
more flexible

23
void print.x() public:
class alpha
{ { beta(alpha*p)

int x; cout<<x; }

public: } a=p;

void read-x() }; }

{ class beta void main()

cin>>x; { {

} int y; alpha a1;

alpha *a; beta b1(&a1);

24
 Member function with parameters of type class it receive object.

 Member function can have parameters of sum class or different class.

 This member function operates on more than one object.

25
Implementing aggregations
Because aggregations are similar to compositions in that they are both part-whole

relationships, they are implemented almost identically, and the difference between them is

mostly semantic.

In a composition, we typically add our parts to the composition using normal member

variables (or pointers where the allocation and deallocation process is handled by the

composition class).

In an aggregation, we also add parts 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.


26
 Consequently, an aggregation usually either takes the objects it is going to point to as

constructor parameters, or it begins empty and the sub-objects are added later via

access functions or operators.

 Because these parts exist outside of the scope of the class, when the class is destroyed,

the pointer or reference member variable will be destroyed (but not deleted).

Consequently, the parts themselves will still exist.

27
A single Employee can not belong to multiple Companies, but if we delete the
Company, Employee object will not destroy. 

28
 In aggregation, parts can belong to more than one object at a time, and the

whole object is not responsible for the existence and lifespan of the parts.

 When an aggregation is created, the aggregation is not responsible for

creating the parts. When an aggregation is destroyed, the aggregation is not

responsible for destroying the parts.

 For example, consider the relationship between a person and their home

address.

29
 In this example, for simplicity, we’ll say every person has an address.

 However, that address can belong to more than one person at a time: for

example, to both you and your roommate or significant other.

 However, that address isn’t managed by the person -- the address probably

existed before the person got there, and will exist after the person is gone.

 Additionally, a person knows what address they live at, but the addresses don’t

know what people live there. Therefore, this is an aggregate relationship.

30
Consider a car and an engine. A car engine is part of the car. And

although the engine belongs to the car, it can belong to other things

as well, like the person who owns the car. The car is not responsible

for the creation or destruction of the engine. And while the car knows

it has an engine (it has to in order to get anywhere) the engine

doesn’t know it’s part of the car.

31
One might argue, “If a meteor fell out of the sky and crushed the

car, wouldn’t the car parts all be destroyed too?” Yes, of course. But

that’s the fault of the meteor. The important point is that the car is

not responsible for destruction of its parts (but an external force

might be).

32
Properties of Aggregations
• There are certain properties associated with objects in an aggregation that
make them different from normal associations.

• These may be classed as follows

Transitivity: If A is part of B and B is part of C then A is part of C.

Antisymmetry : If A is part of B, then B is not part of A. (i.e.not a simple


association).

Propagation : The environment of the part is the same as that of the


assembly.
33
• Aggregation can be fixed, variable or recursive

• These may be classed as follows

Fixed : The particular numbers and types of the component parts are
pre-defined.

Variable : The number of levels of aggregation is fixed, but the number of


parts may vary.

Recursive: The object contains components of its own type. (like a Russian
doll)

34
EXAMPLE 1

35
#include<iostream.h>

class Employee
{
public:

Employee(char *name){
cout<<"Employee::ctor\n";
myName_p = new char(sizeof(strlen(name)));
myName_p = name;
}

char* disp(){return(myName_p);};

~Employee()
{
cout<<"Employee:dtor\n\n";
delete (myName_p);
}
36
private: ~Company()
char *myName_p;
}; {
cout<<"Company:dtor\n\n";
class Company
{ myEmp_p = NULL;
public: };
Company(char * compName,
Employee* emp){ private:
cout<<"Company::ctor\n"; char *name;
name = new
char(sizeof(strlen(compName))); Employee *myEmp_p;
name = compName; };
myEmp_p = emp;
};

37
int main()
Company comp("MS", &emp);
{ } // here Company object will be deleted, whereas Employee
cout<<"\nExample of Aggregation object is still there
Relationship \n";
cout<<"-----------------------------------------\n\n"; cout<<"At this point Company gets deleted...\n";
cout<<"\nBut Employee-"<<emp.disp();
cout<<" is still there\n";
{
cout<<"Here, an Employee-Gokula krishnan
} //here Employee object will be deleted
works for Company-MS \n";
Employee emp(“Gokula krishnan");
return(0);
}
{
38
output:
-------

Example of Aggregation Relationship


-----------------------------------------

Here, an Employee-Keerti works for Company-


MS
Employee::ctor
Company::ctor
Company:dtor

At this point Company gets deleted...

But Employee-Keerti is still there


Employee:dtor
39
EXAMPL
E2

40
std::string getName() { return m_name; }
#include <string> };
#include <iostream>  
  class Department
class Teacher {
{ private:
private:     Teacher *m_teacher; // This dept holds only one teacher for
    std::string m_name; simplicity, but it could hold many teachers
   
public: public:
    Teacher(std::string name)     Department(Teacher *teacher = nullptr)
        : m_name(name)         : m_teacher(teacher)
    {     {
    }     }
  };
     41
int main()
{
    // Create a teacher outside the scope of the Department
    Teacher *t1 = new Teacher("Bob"); // create a teacher
    Teacher *t2 = new Teacher("Frank");
    Teacher *t3 = new Teacher("Beth");
 
    {
        // Create a department and use the constructor parameter to pass
        // the teacher to it.
        Department dept; // create an empty Department
        dept.add(t1);
        dept.add(t2);
        dept.add(t3);
 
        std::cout << dept;
 
    } // dept goes out of scope here and is destroyed
42
std::cout << t1->getName() << " still exists!\n";
    std::cout << t2->getName() << " still exists!\n";
    std::cout << t3->getName() << " still exists!\n";
 
    delete t1;
    delete t2;
    delete t3;
  This should print:
    return 0; Department: Bob Frank Beth
} Bob still exists!
Frank still exists!
Beth still exists!

43
COMPOSITION
Composition is a restricted form of Aggregation in which two entities are

highly dependent on each other.

 It represents part-of relationship.

 In composition, both the entities are dependent on each other.

 When there is a composition between two entities, the composed

object cannot exist without the other entity.

44
To qualify as a composition, an object and a part must have the following

relationship:

 The part (member) is part of the object (class)

 The part (member) can only belong to one object (class) at a time

 The part (member) has its existence managed by the object (class)

 The part (member) does not know about the existence of the object

(class)

45
 A good real-life example of a composition is the relationship between a

person’s body and a heart. Let’s examine these in more detail.

 Composition relationships are part-whole relationships where the part

must constitute part of the whole object.

 For example, a heart is a part of a person’s body. The part in a

composition can only be part of one object at a time.

 A heart that is part of one person’s body can not be part of someone

else’s body at the same time.


46
 In a composition relationship, the object is responsible for the existence of

the parts.

 Most often, this means the part is created when the object is created, and

destroyed when the object is destroyed.

 But more broadly, it means the object manages the part’s lifetime in such a

way that the user of the object does not need to get involved.

 For example, when a body is created, the heart is created too. When a

person’s body is destroyed, their heart is destroyed too.

 Because of this, composition is sometimes called a “death relationship”.

47
  The part doesn’t know about the existence of the whole.

 Your heart operates blissfully unaware that it is part of a larger structure.

 We call this a unidirectional relationship, because the body knows about

the heart, but not the other way around.

  A heart can be transplanted from one body to another.

 However, even after being transplanted, it still meets the requirements

for a composition (the heart is now owned by the recipient, and can only

be part of the recipient object unless transferred again).

48
House can contain multiple rooms there is no independent life for room
and any room can not belong to two different house. If we delete the house
room will also be automatically deleted. 

49
EXAMPLE 1

50
#include<iostream.h>

class Employee
{
public:

Employee(char *name){
cout<<"Employee::ctor\n";
myName_p = new char(sizeof(strlen(name)));
myName_p = name;
}

char* disp(){return(myName_p);};

~Employee()
{
cout<<"Employee:dtor\n\n";
delete (myName_p);
} 51
private: ~Company()
char *myName_p;
}; {
cout<<"Company:dtor\n\n";
class Company
{ myEmp_p = NULL;
public: };
Company(char * compName, Employee*
emp){
cout<<"Company::ctor\n"; private:
name = new
char(sizeof(strlen(compName))); char *name;
name = compName; Employee *myEmp_p;
myEmp_p = emp;
}; };
52
int main()
{
cout<<"\nExample of Aggregation Relationship \n";
cout<<"-----------------------------------------\n\n";

{
cout<<"Here, an Employee-Keerti works for Company-MS \n";
Employee emp("Keerti");

{
Company comp("MS", &emp);
} // here Company object will be deleted, whereas Employee object is still
there

cout<<"At this point Company gets deleted...\n";


cout<<"\nBut Employee-"<<emp.disp();
cout<<" is still there\n";

} //here Employee object will be deleted

return(0);
53
}
#include<iostream.h>

class House;

class Room
{
public:

Room()
{
};

static void createRoom_v(Room* (&room),


House* hse, char* name)
{
room = new Room(hse, name);
}
54
Room(House* hse, char* myName)
{
cout<<"Room::ctor\n";
myHse_p = hse;

if(NULL != myHse_p)
{
name_p = new char(sizeof(strlen(myName)));
name_p = myName;
}
else
{
cout<<"Oops House itself is not Created Yet ...\n";
}
55
};
~Room()
static void initList_v(Room *(& roomsList_p)[3])
{
{
cout<<"Room:dtor\n";
roomsList_p[3] = new Room[3];
myHse_p = NULL;
}
delete (name_p);
};
private:
void disp()
House * myHse_p;
{
char * name_p;
cout<< name_p;
};
cout<<"\n";
}

56
class House
{ Room* myRoom;
public: Room::createRoom_v(myRoom, this, "Kitchen");
roomsList_p[0] = myRoom;
House(char *myName)
{ Room::createRoom_v(myRoom, this, "BedRoom");
cout<<"House::ctor\n"; roomsList_p[1] = myRoom;
name_p = new char(sizeof(strlen(myName)));;
name_p = myName; Room::createRoom_v(myRoom, this, "Drwaing
Room");
Room::initList_v(roomsList_p); roomsList_p[2] = myRoom;
}

57
~House() if(roomsList_p[i] != NULL)

{ {

delete (roomsList_p[i]);
cout<<"House:dtor\n";
}
unsigned int i;

cout<<"Delete all the Rooms ...\n"; delete [] roomsList_p;

for(i=0; i<3; ++i) delete (name_p);

}
{
58
if(NULL != roomsList_p[i])
void disp()
{
{
roomsList_p[i]->disp();
cout<<"\n\nName of the
}
House :"<<name_p;
}
cout<<"\n\n";
if(roomsList_p != NULL)
}
{
}
unsigned int i;
cout<<"\n\nRooms details...\n";
private:
for(i=0; i<3; ++i)
char* name_p;
{
Room* roomsList_p[3];
};
59
int main()
{

cout<<"\nExample of Composition Relationship\n";


cout<<"-----------------------------------------\n\n";
House hse("Vishranti Nilaya");

cout<<"\n\nHouse details...\n";
hse.disp();

cout<<"Here House itself creates the Rooms and


Deletes as well, before it gets deletd...\n";

return(0);
} 60
output:
-------
Example of Composition Relationship
-----------------------------------------

House::ctor
Room::ctor
Room::ctor
Room::ctor
House details...

Name of the House :Vishranti Nilaya

Rooms details...
Kitchen
BedRoom
Drwaing Room

Here House itself creates the Rooms and Deletes as well, before it gets
deletd...
House:dtor
Delete all the Rooms ...
Room:dtor
Room:dtor
Room:dtor
61
EXAMPLE 2

62
class Fraction
{
private:
int m_numerator;
int m_denominator;
public:
Fraction(int numerator=0, int denominator=1):
m_numerator(numerator), m_denominator(denominator)
{
// We put reduce() in the constructor to ensure any fractions we make get reduced!
// Since all of the overloaded operators create new Fractions, we can guarantee this will get called
here
reduce();
}
63
};
 This class has two data members: a numerator and a denominator.

 The numerator and denominator are part of the Fraction (contained within it).

 They can not belong to more than one Fraction at a time.

 The numerator and denominator don’t know they are part of a Fraction, they

just hold integers.

 When a Fraction instance is created, the numerator and denominator are

created.

 When the fraction instance is destroyed, the numerator and denominator are

destroyed as well.

64
 While object composition models has-a type relationships (a body has-a heart, a

fraction has-a denominator), we can be more precise and say that composition

models “part-of” relationships (a heart is part-of a body, a numerator is part of a

fraction).

 Composition is often used to model physical relationships, where one object is

physically contained inside another.

 The parts of a composition can be singular or multiplicative -- for example, a

heart is a singular part of the body, but a body contains 10 fingers (which could

be modeled as an array).

65
AGGREGATION VS COMPOSITION
1.Dependency: Aggregation implies a relationship where the child can
exist independently of the parent. For example, Bank and Employee,
delete the Bank and the Employee still exist. whereas Composition
implies a relationship where the child cannot exist independent of the
parent. Example: Human and heart, heart don’t exist separate to a Human
2.Type of Relationship: Aggregation relation is “has-a” and composition
is “part-of” relation.
3.Type of association: Composition is a strong Association whereas
Aggregation is a weak Association.

66
COMPOSITION AGGREGATION
Type of association (has a) relationship Type of association (has a ) relationship
Strong relationship in terms of weight Weak relationship in terms of weight
EXAMPLE 1: Organization and department: Example 1: Pond and Duck:
Here without organization there won’t be any If the pond is destroyed the duck can go to some
department but without department we can have other pond. It is a weak relation between pond and
organization (ie. Here if we destroy organization the duck.
department also destroyed but if department is
destroyed there is no problem for organization )

EXAMPLE 2: House and Room: Here without room Example 2: Organization and employee
there is a possibility of a house but without house If organization is destroyed the employee can find
there is no possibility of room (ie. Here if we another organization so it is also a weak
destroy house the department also destroyed but if relationship.
department is destroyed there is no problem for
organization )
Symbol: Symbol:
Organization dept Organization employee
67
COMPOSITION AGGREGATION
public class Car { public class Organization {
//final will make sure engine is initialized private List employees;
private final Engine engine;
}
public Car(){
engine = new Engine(); public class Person {
} private String name;
} }
class Engine {
private String type;
}

68
Aggregation v. Inheritance
A classification hierarchy shows how classes inherit from each other and shows the
position in the hierarchy as 'a kind of' relationship.

 i.e. An Estate car is 'a kind of' car and a car is 'a kind of‘ vehicle.

Associations also form hierarchies but they are very different from inheritance. These
are described by the following terms
• Aggregation
• Composition
• Part-Whole
• A Part Of (APO)
• Has a
• Containment

69
In this type of hierarchy, classes do not inherit from other classes but are composed of
other classes.

This means that an object of one class may have it's representation defined by other
objects rather than by attributes.

The enclosing class does not inherit any attributes or methods from these other included
classes.

This means that this is a relationship (association) between objects.

An object of the enclosing class is composed wholly or partly of objects of other classes.

Any object that has this characteristic is know as an aggregation

70
THANK YOU
71

You might also like