Given a class “A” exists and is correct. What would be some of the negative results of using a reference to “A” instead of a pointer in a class “B”. That is:
// In Declaration File
class A;
class B
{
public:
B();
~B();
private:
A& a;
};
// In Definition File
B::B(): a(* new A())
{}
B::~B()
{
delete &a;
}
Omitted extra code for further correctness of “B”, such as the copy constructor and assignment operator, just wanted to demonstrate the concept of the question.
The immediate limitations are that:
Ait refers to, but you cannot reallocate or reassignaduringB‘s lifetime.amust never be0.Thus:
Bshould not be copy constructible, unless you teachAand its subtypes to clone properly.Bwill not be a good candidate as an element of collections types if stored as value. A vector ofBs 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:
ais assignable and assignment is reachable withinB.