Let's assume I have two classes A and B in C++. Both classes have some private variables and both are friends. Both classes have some simple public function (no function call in these functions), that uses variables from both A and B.
I give you an code-example of the idea:
class A;
class B;
//Here I declare the variables
class A{
friend class B;
private:
double a=2.;
};
class B{
friend class A;
private:
double b=2.;
};
//Now I try to declare the functions
//I know, I do a redefinition now, but actually I just
//like to define the functions after the variables, such
//that the compiler knows the variables my functions
//like to use.
class A{
public:
double fun(B Btest){return Btest.b+2*a;}
};
class B{
public:
double fun(A Atest){return Atest.a+b;}
};
int main(){
A Atest;
B Btest;
double s=Btest.fun(Atest);
return 0;
}
If I were the compiler, I also would not accept that code because there might be ugly circular dependencies, but in my case, I am sure, there are no circles. Is there a nice way to tell my compiler to do something like this?
Here is the solution, I didn't really understood the concept of declaration and definition in detail:
What is the difference between a definition and a declaration?
class A;
class B;
class A{
friend class B;
public:
double fun(B);
private:
double a=2.;
};
class B{
friend class A;
public:
double fun(A);
private:
double b=2.;
};
double A::fun(B Btest){return Btest.b+a;}
double B::fun(A Atest){return Atest.a+b;}
int main(){
A Atest;
B Btest;
double s=Btest.fun(Atest);
return 0;
}