Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solving cyclical dependency for friend classes

Tags:

c++

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?

like image 952
Joe Avatar asked Sep 05 '25 03:09

Joe


1 Answers

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?

like image 84
Alok Save Avatar answered Sep 07 '25 23:09

Alok Save