LET'S TALK TECHNICAL

This blog is intended to help people prepare for the job interviews and improve their analytical skills. We have posted difficult datastructures and algorithm questions and puzzles. Interview experiences section is for the people to post their interview experiences.Views expressed here are of their personal and the blog author doesn't take any responsibility for the same.

-

Followers

Jobs

Wednesday, February 13, 2008

Difference Between Composition and Aggregation in Object Oriented Programming?

Both are one way of extending a class.

In a composition relationship, the whole has sole responsibility for the disposition of its parts, or as you put it above, the whole "controls the lifetime of" the part. In order for the whole
to have "sole disposition" or "control the lifetime" of its parts, the whole must be the only object that knows of the parts existence.

C++ Code Example:

class Whole {
Part* part;
public:
Whole(): part( 0 ) { }
~Whole() { delete part; }
};
Part is created inside Whole class constructor and it is destroyed when whole is destroyed.

Real Life Example:
University and Departments have a composition relationship. When University is created all the departments are created with it. When University is removed departments will not have the existance of their own.


In aggregation relationship, the part object reference can be re-used. Usually creation of part object is not the responsibility of the ‘whole ‘ object. It would have been created somewhere else, and passed to the ‘whole’ object as a method argument. Whole object will not have control on the lifetime of the part object.

class Whole {
Part* part;
public:
Whole() { }
~Whole() { }
};

Real Life Example:

University and Professors are in aggregation relationship. When University is formed professors will come and join the University. But, when University is removed Professors will still exists and they can work in other Universities.

Popular Posts