Jason
Jason

Reputation: 551

Circular dependencies in C++ classes using references

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?

Upvotes: 1

Views: 129

Answers (1)

user7860670
user7860670

Reputation: 37503

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.

Upvotes: 4

Related Questions