Preprocessors in Composition and Aggregation

I keep thinking I've got my mind wrapped around composition but every time I try to implement it, I get a plentiful output of errors.

If this hypothetically was how I was going to use composition, what would I need to include?

1
2
3
4
5
6
7
8
9
10
11
12
class Bar
{
    Baz baz;
};

class Foo
{
private:
    Bar bar;
public:
    void someFunctionToUseBar();
};


As for aggregation, I can't seem to wrap my head around any explanation I've read so far. 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?
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.
I guess my example with the Foo and Bar classes was a bit redundant, I didn't realize at the time. Basically with composition, the compiler has to know what the class is which is where the "copy and paste" preprocessor (include) comes into play. Anytime I have an object inside another class which is not already defined in the same .h file it needs to be included. and just a little thinking out loud, that brings in the benefit of putting multiple classes in the same header file?

That aggregation explanation made a lot of sense to me. In a really simplified general version, aggregation is a uses-a relationship and composition is a has-a relationship?
Topic archived. No new replies allowed.