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?

4
  • 2
    Forward declarations and separating header + source or think your design over. Commented Sep 30, 2019 at 7:48
  • @nada that doesn't cover the actual construction of the objects, though. Commented Sep 30, 2019 at 7:49
  • 1
    Yes, the construction of the objects is point I can't get past. Commented Sep 30, 2019 at 7:50
  • Regarding the construction, it's not simply possible with your current design and implementation. Commented Sep 30, 2019 at 8:01

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Isn't that an UB? passing uninitialized m_b to the constructor of m_a?
@Quest Accessing passed reference will be UB, but just passing a reference (or a pointer) is not.
This is an interesting approach, thanks, I'll give it a try.
@Quest Actually, that has been asked in a separate question already...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.