Hi All,
Below is the code of implementation of aggregation in c++. In this code class bar object will be contained in class a but
class a won't act as a owner of class bar and due to this bar object is deleted after class a's life time ends.
Now i would like to know as i never experienced aggregation before :

(1) How bar object before deletion can be linked with other classes as class 'a; still doesn't own the bar class object .
(2) Do we need to provide the helper function to delete the bar object in case if it interacts with other classes . So that it can be deleted after last interaction.
(3) As Class a don't own the class bar then can still assocation be used instead of aggregation by passing the bar object from class a's any method.

#include <iostream>

using namespace std;
class bar

void show()
cout<<"Travel the world";

~bar(){cout<<"b's destructor"<<endl;}

class a   
bar *b;
int * p;

a(bar *b,int* p):b( b),p(p)



cout<<"a's destructor"<<endl;
int main()
int *p= new int (10);
bar* obj1= new bar;
a obj(obj1,p);

delete p;

delete obj1;// obj1 still exist after obj is out of the scope

return 1;

The problem here is ownership and responsibility.

The aggregate class would normally take ownership of the object being passed to it. [Sometimes that aggregate class would build the object via a factory object -- but let us keep this simple].

So in words this is what I think you want to happen:

(a) allocate memory for an new object [e.g. int* p=new int[10];]
(b) Populate the object : [e.g. for(int i=0;i<10;i++) p[i]=i; ]
(c) give the object to the aggregate class AND let it take ownership [e.g.
aggregateClass obj(b,p) : ; ]
(d) when objB goes out of scope the destructor of bar is called.
[e.g. aggregateClass:~aggregateClass() { delete b; delete [] p; } ]

The important think is one delete per new, and the aggregate class deletes the memory it is given to manage.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.