Type of composition where no ownership is implied.


Thus (sub) objects are independent of each other, and are not destroyed when the aggregate object is destroyed.


Aggregate objects contain pointers or references to other objects, created outside of the class. When the aggregate object is destroyed and their pointers or references to the sub-objects goes out of scope, the sub-objects continue to exist.


Composition is creating a Person object, that gets destroyed when composition object goes out of scope


Whereas aggregation is creating a Person object that still exists when aggregation goes out of scope.


In this example, a sub-object is created (on line 34) independently of any other class. It is then used (line 38) in the constructor parameter when creating the aggregate object. When the aggregate object goes out of scope (line 39), the sub-object continues to exist as can be seen on line 40, until it is deleted on line 42:

#include <string>
using namespace std ;

class Person {
		string name ;
		Person(string myStr): name(myStr) {
			cout << "Person Created: " << myStr << endl ;
			cout << "Person Destroyed: " << name << endl ;
	string getName(){ return name ;}

//Aggregation. Sub-objects live on when parent object destroyed
class MegaCorp{
		Person* investBanker;
		MegaCorp(Person* overvPaid){
			investBanker = overvPaid;
			cout << overvPaid->getName() << " got a job with MegaCorp!" << endl ;
			cout << investBanker->getName() << " got the sack from MegaCorp!!!" << endl ;
			investBanker = NULL;

int main(){
	Person* female = new Person("Sharon") ;

	cout << female->getName() << " Lives!" << endl ;
		MegaCorp tempJob(female) ;
	cout << female->getName() << " Lives!" << endl ;

	delete female ;

	return 0 ;

Compile & Run:

Person Created: Sharon
Sharon Lives!
Sharon got a job with MegaCorp!
Sharon got the sack from MegaCorp!!!
Sharon Lives!
Person Destroyed: Sharon

Leave a Reply