How to initialize const circular reference members

804 views Asked by At

For example, I have two classes

class Foo;
class Bar;

class Foo {
  const Bar &m_bar;
  ...
};

class Bar {
  const Foo &m_foo;
  ...
};

Let foo is object of Foo and bar is object of Bar. Is there any way (normal or "hacking") to create/initialize foo and bar that their members m_bar and m_foo would referenced to each other (I mean foo.m_bar is bar and bar.m_foo is 'foo')?

It is allowed to add any members to Foo and Bar, to add parents for them, to make they templates and so on.

2

There are 2 answers

8
James Kanze On BEST ANSWER

What is the linkage of foo and bar? If they have external linkage, you can write something like:

extern Foo foo;
extern Bar bar;

Foo foo( bar );
Bar bar( foo );

(I'm assuming here that it is the constructors which set the reference to a parameter.)

This supposes namespace scope and static lifetime, of course (but an anonymous namespace is fine).

If they are class members, there's no problem either:

class Together
{
    Foo foo;
    Bar bar;
public:
    Together() : foo( bar ), bar( foo ) {}
};

If they're local variables (no binding), I don't think there's a solution.

EDIT:

Actually, the local variables have a simple solution: just define a local class which has them as members, and use it.

0
Teh Suu On

This can't work if i understand your Problem correctly, since to create an Object Bar you need Foo and vice versa. You must not use References but an Pointer instead. Where you can create both Objects separatley and then set Bar to Foo and Foo to Bar.

class Foo
{ 
public:
   Foo();
   void setBar( const Bar* bar ){ _bar = bar; }

private:
   const Bar* _bar;
}
// class Bar analog to Foo


void xxx:something(void)
{
   Foo* f = new Foo;
   Bar* b = nee Bar;
   f->setBar(b);
   b->setBar(f);
   ...
}