Some advantages of owning an instance (class B { A a; };):
- No need to worry about creation and destruction of
a because it happens automatically.
- No need to worry that
a might be a dangling or null pointer.
- Memory locality:
a lives where instances of B live. If you have a large array of Bs and access each B's A in turn, this could make a significant speed difference.
- Memory efficiency: no storage for a pointer is needed.
To make a huge sweeping generalization, one could say that this approach is faster and safer.
Some advantages of owning a pointer (class B { A *a; };):
- Polymorphism:
a can actually point to a subclass of A.
a can be reassigned without needing to copy an instance of A.
a can live independently of B or even be owned by another object entirely.
a can be null, freeing up memory if it's not always needed.
To make another huge sweeping generalization, one could say that this approach is more flexible.