What are some of the disadvantages of using a reference instead of a pointer?
The immediate limitations are that:
- You cannot alter a reference's value. You can alter the
A
it refers to, but you cannot reallocate or reassigna
duringB
's lifetime. a
must never be0
.
Thus:
- The object is not assignable.
B
should not be copy constructible, unless you teachA
and its subtypes to clone properly.B
will not be a good candidate as an element of collections types if stored as value. A vector ofB
s would likely be implemented most easily asstd::vector<B*>
, which may introduce further complications (or simplifications, depending on your design).
These may be good things, depending on your needs.
Caveats:
- slicing is another problem to be aware of if
a
is assignable and assignment is reachable withinB
.
You can't change the object referred to by a after the fact, e.g. on assignment. Also, it makes your type non-POD (the type given would be non-POD anyway due to the private data member anyway, but in some cases it might matter).
But the main disadvantage is probably it might confuse readers of your code.