Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two classes with friend methods in C++

Currently I am reading a book about C++ and it has some exercises. One of the exercises asks to build two classes where each has a friend method for another. My current guess looks like this:

#include <iostream>

using std::cout;
using std::endl;

class Y;

class X{
public:
   void friend Y::f(X* x);
   void g(Y* y){cout << "inside g(Y*)" << endl;}
};

class Y{
public:
   void friend X::g(Y* y);
   void f(X* x) {cout << "inside f(X*)"  << endl;}
};

But my guess does not compile because class X have void friend Y::f(X* x); method declaration. How can I solve the puzzle? Give me some more guesses, please.

like image 641
gkuzmin Avatar asked Jun 17 '13 20:06

gkuzmin


1 Answers

In order to declare a function as a friend, the compiler has to have seen it first, and C++ does not allow forward declarations of member functions. Therefore what you are trying to do is not possible in the way you want. You could try using the "passkey" method from here.

Alternatively, you could replace void friend Y::f(X* x); with friend class Y;.

like image 54
Cory Klein Avatar answered Nov 01 '22 18:11

Cory Klein