If this hypothetically was how I was going to use composition, what would I need to include? |
Remember... #include is just a glorified copy/paste.
In your case, the 'Baz' class would have to be defined above that 'Bar' class. If Baz is defined in another header, this means baz.h would have to be #included above the Bar class.
Further reading:
http://www.cplusplus.com/forum/articles/10627/
As for aggregation, I can't seem to wrap my head around any explanation I've read so far. |
It's a matter of ownership.
The
owner of an object is the one responsible for creation/destruction of it. The lifetime of the object cannot exceed the lifetime of its owner, because when the owner is destroyed, so are all of the things it owns.
Composition implies ownership. Aggregation does not.
With composition, in your example, the 'Foo' class owns that 'bar' object. So if I create a Foo object:
Foo a;
, then 'a' becomes the owner of
a.bar
Conversely, with aggregation:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
class Foo
{
Bar* bar;
public:
Foo(Bar* b) : bar(b) {}
};
int main()
{
Bar bar;
Foo foo(&bar);
}
|
Here, Foo uses a Bar object, but it does not own it. main() owns the bar object. The 'foo' object can be destroyed and it will not impact the lifetime of the 'bar' object.
One website said you don't really need to use aggregation if you have proper control of both composition and association. Any truth to this? |
As always, use the right tool for the job.