You can't do that even in principle, because a single A
object would contain a B
which contains another A
, which contains another B
and another A
...
If you just want a reference, you can simply do
class B; // forward declaration
class A {
B& b_; // reference
public:
explicit A(B& b) : b_(b) {}
};
class B {
A a_;
public:
B() : a_(*this) {}
};
Now each B
contains an A
which refers to the B
in which it sits.
Do note however that you can't really do anything with b
(or b_
) inside A
's constructor, because the object it refers to hasn't finished creating itself yet.
A pointer would also work - and of course A
and B
can both have references instead of B
containing an immediate object.