2

On the most basic level, I need a method from a class to access private data from another class, such as:

foo.h:

class foo{
    void method( void );
}

bar.h:

class bar{
   friend void foo::method( void );
}

However, method needs to know which object to be accessing, making it look more like this:

foo.h:

class foo{
    void method(bar* point);
}

bar.h:

class bar{
    friend void foo::method(bar* point);
}

However, as you can see this gives cyclical dependency: bar would need foo.h for declaring a friend, and foo would need bar.h as it uses a bar pointer. How else would the method know which object to access?

Joe
  • 398
  • 4
  • 15

1 Answers1

4

If you find yourself in a cyclic dependency, it is probably best to review your design once. Once you review the design and if you still feel the need for the cyclic dependency, You need to use a Forward declaration of the class.

class bar;
class foo
{
    void method(bar* point);
}

Good Read:
When can I use a forward declaration?

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • I've done this - they are stored in separate header files, which seems to be the problem - The first won't compile without the other, and so on and so fourth – Joe Apr 29 '13 at 16:29
  • Really, nothing to add? I need an answer to get this working! – Joe Apr 29 '13 at 18:24
  • @Joe Have you tried adding forward declarations for each class to both files? – David G Apr 29 '13 at 21:06
  • @0x499602D2, Yes I have. To no avail. the first won't compile because it can't include the second, because it can't compile because the first can't be included because it has not yet been compiled... – Joe Apr 30 '13 at 21:19