Reputation: 1406
Let's say I have two class A and B. There are 2 ways in which class B can use A.
First:
class B
{
A *a;
}
Second:
class B
{
A a;
}
Why most of the C++ libraries prefer to use First
version as compared to Second
. What could be the disadvantage of using Second approach. Does it relate to Stack vs Heap assignment? Please clarify.
Upvotes: 4
Views: 1933
Reputation: 182073
Some advantages of owning an instance (class B { A a; };
):
a
because it happens automatically.a
might be a dangling or null pointer.a
lives where instances of B
live. If you have a large array of B
s and access each B
's A
in turn, this could make a significant speed difference.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; };)
:
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.
Upvotes: 8