How to make a circular dependency work?

Is there a way to make this circular dependency work?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class A;	    //forward declare
class B
{
    private:
	A& refA;
    public:
	B(A& refA) : refA(refA) {}
};

class A
{
    private:
	B b;
    public:
	A(B b) : b(b) {}
};

int main()
{
	A a(b);     //error: 'b' was not declared in this scope
	B b(a);
}

The compile error is on line 20:
error: 'b' was not declared in this scope

How to pass b to constructor before b is instantiated?

Thank you.
Last edited on
This solution compiles.
It initializes B::ptrA after both classes are instantiated.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class A;	        //forward declare
class B
{
    private:
	A* ptrA;
    public:
	void begin(A* a)
        {
            ptrA = a;
        }
};

class A
{
    private:
	B b;
    public:
	A(B b) : b(b) {}
};

int main()
{
	B b;
        A a(b);
        b.begin(&a);
}


The following code is similar; but it uses a reference refA in place of the pointer prtA. It does not compile:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class A;	        //forward declare
class B
{
    private:
	A& refA;
    public:
	void begin(A& a)
        {
            refA = a;   //error: invalid use of incomplete type 'class A'
        }
};

class A
{
    private:
	B b;
    public:
	A(B b) : b(b) {}
};

int main()
{
	B b;
        A a(b);
        b.begin(a);
}

Why does the reference not compile?
Last edited on
Why does the reference not compile? Why does the reference not compile?


References must be initialized to refer to something. Here, you don't initialize the reference.
Thanks cire.
> This solution compiles
that "solution" has different behaviour.
A(B b) : b(b) {} is doing a copy of the parameter. However at that point you have not yet bind the pointer.

You've got main::b.ptr that points to main::a
but main::a.b.ptr is uninitialized.


¿do you need main::b?
1
2
A a{ params };
A(params): b( params, this ){}
Last edited on
Topic archived. No new replies allowed.