Aggregation (object-oriented programming)

This is an old revision of this page, as edited by 64.18.178.33 (talk) at 14:48, 28 March 2005. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Aggregation is a form of composition where one looks at the system as a whole rather than as parts. It is also based on has-a relationship and is implemented by creating objects of other classes inside the class. An example will be a car class which is an aggregation of different classes like wheel, engine, body etc.

Aggregation differs from composition in that aggregation indicates ownership; that is, in aggregation, when the containing object is destroyed, so are the contained objects. In composition, this is not necessarily true. For example, a university consists of various departments (e.g., chemistry), and each department contains a number of professors. These relationships can be modelled as aggregation since if the university disbands the departments certainly will, and if a department disbands, the professors in that department will no longer have jobs at the university (and no longer exist in this scope). On the other hand, suppose several professors are on a committee. This relationship is best modelled as a composition—but not an aggregation—since the disbanding of the committee would not mean the professors lost their jobs.

Aggregation is usually implemented such that an object contains another object. For example, in C++:

class Professor;

class Department
{
  ...
  private:
  Professor faculty[20];
  ...
};

In composition, the object may only contain a reference or pointer to the object:

class Professor;

class Committee
{
  ...
  private:
  Professor* members[5];
  ...
};