5

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.

Kara
  • 6,115
  • 16
  • 50
  • 57
gkuzmin
  • 2,414
  • 17
  • 24
  • Are you sure that is the exact formulation of the text? – Andy Prowl Jun 17 '13 at 20:07
  • The book was written in English, but was translated to Russian, so I can not be sure that the translator was absolutely correct. But this formulation is interesting enough anyway. – gkuzmin Jun 17 '13 at 20:09
  • 3
    Duplicate of http://stackoverflow.com/questions/6310720/declare-a-member-function-of-a-forward-declared-class-as-friend – Cory Klein Jun 17 '13 at 20:12
  • 1
    @gkuzmin: The thing is, I don't really think it is possible, so unless something else is meant, I would say the answer is "you can't do it". Perhaps the intent was just "granting `Y` access to the non-public members of `X`, and vice versa. In that case you do not need mutual friendship – Andy Prowl Jun 17 '13 at 20:12
  • @CoryKlein's link contains the answer. It's not possible to declare member functions as `friend`, only whole classes or global functions. BTW you should avoid using `friend` at all, there are better design patterns available to replace this construct. – πάντα ῥεῖ Jun 17 '13 at 20:18
  • 2
    @g-makulik - I have to disagree, proper usage of `friend` should be encouraged. One only needs to understand when `friend` improves encapsulation and when it is destructive. (http://stackoverflow.com/a/17443/446554) – Cory Klein Jun 17 '13 at 20:21
  • @CoryKlein There are proper use cases, agreed! But I still think friend should be avoided when possible, or at least when consequences of interface cluttering and unnecessary dependencies are foreseeable in the design. It's even an obsolete dependency stereotype in at least UML 2.2 ... – πάντα ῥεῖ Jun 17 '13 at 20:31

1 Answers1

5

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;.

Community
  • 1
  • 1
Cory Klein
  • 51,188
  • 43
  • 183
  • 243