Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize const circular reference members

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.

like image 701
Loom Avatar asked Sep 13 '13 11:09

Loom


1 Answers

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.

like image 193
James Kanze Avatar answered Oct 07 '22 12:10

James Kanze