2

I've got two objects that need to point to one another... the only problem is that since they are declared in a particular order, one or the other doesn't know about the other object existing. For example:

...
#define foobar_h

class Foo {
  Bar* b;
};

class Bar {
  Foo* f;
};

...

How can I declare these classes so that they'll be happy referencing one another?

Brian D
  • 9,863
  • 18
  • 61
  • 96
  • 1
    This is a common question, and the common answer starts with: do you *really* need a cyclic dependency in your code? There are cases where it makes sense, but in most cases it's a hint that the design can be improved. Think about it. – David Rodríguez - dribeas Feb 23 '12 at 19:49
  • It's a valid point. I end up doing crap like this as it is currently designed: `float x = (*(*bar).foo).getSignal(*bar);` – Brian D Feb 23 '12 at 20:56
  • I have a linked list of foos, and each foo points to a linked list of bars. It's a 2D linked list. Each foo contains raw data, each bar contains a separate set of parameters in relation to its particular bar. I need to operate on the bar with the parameters in foo.. so foo just holds a linked list of foos and bars, while bar holds a linked list of bars, and a pointer back to its head (foo). Probably more detail than you cared to know, but that's what's going on. – Brian D Feb 23 '12 at 21:02

1 Answers1

10

You do a pre-declaration:

class Bar;

class Foo {
  Bar* b;
};

class Bar {
  Foo* f;
};

This makes the compiler know that the type Bar is a class, so it can correctly figure out how to represent a pointer to it.

Of course, this only works when the exact layout and size of values of type Bar are not needed, if you had tried to embed a value with:

class Foo {
  Bar my_bar;
};

You had not been able to succeed, but since you used a pointer it's okay. A reference had also worked, since references don't embed the entire object.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • Derp. I knew it was something simple like that. Thanks. – Brian D Feb 23 '12 at 19:37
  • Note this works for pointers and references but not instance members which need the definition at declaration. – AJG85 Feb 23 '12 at 19:39
  • AJG85: You can't have two classes that contain each other as members though. It should always be possible to have one class refer to the other only by pointer/reference. – Mooing Duck Feb 23 '12 at 20:03
  • Those are called _forward-declarations_. Actually, though, they simply are class declarations. (See why at the end of [this answer](http://stackoverflow.com/questions/1410563/what-is-the-difference-between-a-definition-and-a-declaration/1410632#1410632).) – sbi Feb 23 '12 at 20:04