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?
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:
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);
}
> 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.