Aggregation and Composition
Aggregation and Composition
●
Inheritance is a “kind of” relationship.
●
Aggregation is a “has a” relationship.(weak
relationship).
●
Composition is a “consists of” relationship.
Aggregration
An aggregation is a specific type of composition where no
ownership between the complex object and the subobjects is
implied. When an aggregate is destroyed, the subobjects are
not destroyed.
For example, consider the math department of a school, which is
made up of one or more teachers. Because the department
does not own the teachers (they merely work there), the
department should be an aggregate. When the department is
destroyed, the teachers should still exist independently (they
can go get jobs in other departments).
• Aggregation differs from ordinary composition in that
it does not imply ownership. In composition, when the
owning object is destroyed, so are the contained
objects. In aggregation, this is not necessarily true.
For example, a university owns various departments
(e.g., chemistry), and each department has a number
of professors. If the university closes, the
departments will no longer exist, but the professors in
those departments will continue to exist. Therefore, a
University can be seen as a composition of
departments, whereas departments have an
aggregation of professors. In addition, a Professor
could work in more than one department, but a
department could not be part of more than one
university.
Aggregation Example
#include<iostream>
#include<string.h>
class professor
using namespace std; {
class department
{
int pid;
public: int exp;
char name[20];
department()
department *d;
{ public:
strcpy(name,"abc");
professor(int a,int b, department *d)
} {
~department()
{
pid=a;
cout<<"department class destroyed"<<endl; exp=b;
}
this->d=d;
}; }
class professor
~professor()
{ {
int pid;
int exp;
cout<<"professor class destroyed.
department *d; "<<endl;
public:
professor(int a,int b, department *d)
{ }
pid=a;
exp=b;
this->d=d; };
}
~professor()
main()
{ {
cout<<"professor class destroyed. "<<endl;
department D;
} {
};
professor p(1,2,&D);
main() }
{
department D;
cout<<"At this point professor gets deleted but
{ department is still there"<<endl;
professor p(1,2,&D);
}
}
cout<<"At this point professor gets deleted but department is still there"<<endl;
}
Composition Example
#include<iostream> class person
using namespace std; {
class birthday string name;
{ birthday b;
int date, month,year; public:
public: person(string n,int d,int m,int y):b(d,m,y)
birthday(int d,int m,int y) {
{ name=n;
date=d; cout<<"person constructor"<<endl;
month=m; }
year=y; void show()
cout<<"birthday constructor"<<endl; {
} b.display();
~birthday() cout<<name;
{ }
cout<<"birthday destructor"<<endl; ~person()
} {
void display() cout<<"person destructor"<<endl;
{ }
};
cout<<date<<"/"<<month<<"/"<<year<<endl; int main()
} {
}; person ob("abc",12,10,2023);
ob.show();
}