1

I have two objects of classes (A and B) which must be able to refer to each other, e.g.:

class A {
public:
    A(B& b);

private:
    B& b;
};

class B {
public:
    B(A& a);

private:
    A& a;
};

But I can't do this:

A a(b);
B b(a);

With pointers this would be easy, as a pointer can be NULL. How can I achieve the same result using references, or is it not possible?

Jason
  • 531
  • 6
  • 19

1 Answers1

4

One solution is to pack both of them into third object and initialize at constructor:

class C
{
    public: A m_a;
    public: B m_b;

    public: C(void): m_a{m_b}, m_b{m_a} {}
};

Note that this approach requires class A not to access passed reference to class B at constructor because object B is not initialized at that point.

user7860670
  • 35,849
  • 4
  • 58
  • 84
  • Isn't that an UB? passing uninitialized `m_b` to the constructor of `m_a`? – Quest Sep 30 '19 at 08:05
  • 4
    @Quest Accessing passed reference will be UB, but just passing a reference (or a pointer) is not. – user7860670 Sep 30 '19 at 08:05
  • This is an interesting approach, thanks, I'll give it a try. – Jason Sep 30 '19 at 08:21
  • @Quest Actually, that has been asked in a [separate question](https://stackoverflow.com/questions/37724668/is-taking-uninitialized-references-of-class-members-during-construction-legal) already... – Aconcagua Sep 30 '19 at 10:13