4

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.

bhavesh
  • 1,343
  • 2
  • 14
  • 23
  • I am not sure why you think the first version is better, I usually use the second. the first one, you should be carefull with class allocation, and deletion, – aah134 Aug 08 '13 at 18:40
  • it depends on how you define `use`? – Hossein Nasr Aug 08 '13 at 18:43
  • "Why most of the C++ libraries prefer to use First version as compared to Second" So you looked into > 50% of all existing C++ libraries? Joking apart, they're different. E.g. [Why not use pointers for everything?](http://stackoverflow.com/q/1064325/420683) and many many other answers. – dyp Aug 08 '13 at 18:43
  • It depends on how A will be used. For example, if you had a getter function on B for A that returned a pointer to it: `A* a = b->getA();` and then b gets deleted, then in the second example, you'd have a dangling pointer `*a` – crush Aug 08 '13 at 18:45
  • You could also store a reference to the instance of class A. – Derek Aug 08 '13 at 18:46
  • Five comments and no one has complained yet that [a raw pointer `A*` shouldn't be an owning pointer](http://stackoverflow.com/a/417635/420683)? I'm baffled ;) – dyp Aug 08 '13 at 18:59

1 Answers1

8

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.

Thomas
  • 174,939
  • 50
  • 355
  • 478
  • 2
    Polymorphism can also be achieved using a reference. All of the advantages of the "pointer" category plus some of the "non-pointer" category can be achieved using a smart pointer. – dyp Aug 08 '13 at 18:45