Composition 27032024 090045am 26072024 100343am
Composition 27032024 090045am 26072024 100343am
Composition 27032024 090045am 26072024 100343am
on
Object Oriented
Programming
Spring
2020
Imran
Siddiqi
Introductio
Innreal-life, complex objects are often
built from smaller, simpler objects. For
example
3
Compositi
on
More specifically, composition is used for
objects that have a has-a relationship to each
other.
5
Composition -
Example
6
class Date Composition -
Example
{
public:
Date( int d= 1, int m= 1, int y= 1900 );
void print() const;
~Date();
private:
int month;
int day;
int year;
};
Date::Date( int mn, int dy, int yr )
{
month = mn;
year = yr;
7
day = dy;}
void Date::print() const
{
cout << month << '/' << day << '/' << year;
}
Date::~Date()
{
cout << "Date object destructor for date ";
cout << endl;
}
8
class Employee
{
public:
Employee( int ,Date, Date );
void print() const;
~Employee();
private:
int ID;
Date birthDate;
Date hireDate;
};
9
void Employee::print() const
{
cout << Emp ID << ", " << ID << " Hired: ";
hireDate.print();
cout << " Birthday:
"; birthDate.print();
cout << endl;
}
Employee::~Employee()
{
}
10
int main()
{
Date birth( 7, 24, 1949 );
Date hire( 3, 12, 1989 );
Employee manager( 123, birth, hire );
return 0;
}
11
Composition
and
Aggregati
on
Composition vs.
Aggregation
► Both represent ‘has-a’
relationship
of the "has
► Composition is a stronger a“
variant relationship
► Aggregation can occur when a class is a collection
or container of other classes, but where the
contained classes do not have a strong life
cycle dependency on the container
► If the container is destroyed, its contents are not.
Composition vs.
Aggregation
► Composition has a strong life cycle
dependency between instances of the
container class and instances of the contained
class(es)
► If the container is destroyed, normally every
instance that it contains is destroyed as well
UML
Notation
Composition
Aggregation
Exampl
► Team has players
esAggregation: If team dissolve, Player will still exists
►
class Test{
public:
Test(int xx =0);
voidprint () const;
private:
int x;
};
Exampl
e
Test::Test (int a ) // Constructor
{ x = a;}
void Test::print() const
{
cout << " x is equal to " << x ;
<< "\n this->x is equal to "<<this->x;
cout << "\n (*this).x is equal to "<< (*this).x <<endl;
}
int
cout
main (void)
{ Test testobject(12);
testobject.print();
return 0;
}
Exampl
elass Point{
c
private:
int x;
int
y;
public: x, int y){
Point(this->x = x;
int
this->y =
y;
}
};
The Composite
Rectangle Class
class
Rectangle
{ private:
Poin upperLeft,
t lowerRight;
public:
Rectangle() {}
Rectangle (Point ul, Point
lr);
Poin GetUpperLeft() const { return upperLeft;
t } GetLowerRight() const { return
Poin SetUpperLeft(Point
void lowerRight; }
Location)
t
{ upperLeft = Location; }
void SetLowerRight(Point
Location)
{ lowerRight = Location;
} int GetArea() const; 23
};