Friendship and circular dependencies
Hello, I would like to know how I could solve the following circular dependency.
class_A.h
------------
#include "../include/class_B.h"
class class_A
{
public:
...
friend void class_B::funct();
};
class_B.h
------------
#include "../include/class_A.h"
class class_B
{
public:
...
void funct();
...
private:
class_A temp;
};
As already suggested to me, a forward declaration doesn´t seem to work. If I insert it in file "class_A.h" then the compiler does not know the member function class_B::funct, and if I insert it in file "class_B.h" the compiler does not know the object class_A.
Thanks a lot in advanced!!
Re: Friendship and circular dependencies
Quote:
Originally Posted by
navarromoral
Hello, I would like to know how I could solve the following circular dependency.
- You could remove the need for a friend declaration.
- You could make the entire class_B a friend of class_A.
- You could class_B::temp a pointer to class_A and only include "class_A.h" in the cpp file for class_B.
Re: Friendship and circular dependencies
thank you for your reply:
The first option is mandatory, so I cannot change it.
The second is what I was trying to avoid.
And the third is the only option left, so I guess I'll do this way. I just wanted to know if there was any other option.
Thanks!
Re: Friendship and circular dependencies
Quote:
Originally Posted by
navarromoral
I just wanted to know if there was any other option.
Maybe a mutual friend free function could accomplish what you want, like this
Code:
void function(); // mutual friend of A and B
class class_A {
friend void function();
public:
};
class class_B {
friend void function();
public:
void funct() {
function();
}
private:
class_A temp;
};
Re: Friendship and circular dependencies
Yes, that could work, I had not thouth of that!!
The problem I see is that it breaks the encapsulation of the classes, but if it works...
Thanks a lot!!
Re: Friendship and circular dependencies
Quote:
Originally Posted by
navarromoral
The problem I see is that it breaks the encapsulation of the classes,
The position of Bjarne Stroustrup (inventor of C++) on this issue is that a shared implementation doesn't weaken the encapsulation of the classes involved. (See The Design and Evolution of C++ in section 2.10 The Protection Model on page 53.)
But if you feel it does then you shouldn't use friend at all.