Search code examples
c++friend

Specify a class member function as a friend of another class?


According to the C++ Primer book, the author mentioned that we can specify a class member function as a friend of another class, instead of the entire class (page 634).

Then, I tested this code:

class A
{
public:
    friend void B::fB(A& a);
    void fA(){}
};
class B
{
public:
    void fB(A& a){};
    void fB2(A& a){};
};

I just wanted the fB() to be friend of class A, not the entire class B. But the above code produced an error: 'B' : is not a class or namespace name. (I am using Visual C++ 2005)


Solution

  • Try putting the B definition before A's:

    class A; // forward declaration of A needed by B
    
    class B
    {
    public:
        // if these require full definition of A, then put body in implementation file
        void fB(A& a); // Note: no body, unlike original.
        void fB2(A& a); // no body.
    };
    
    class A
    {
    public:
        friend void B::fB(A& a);
        void fA(){}
    };
    

    A needs the full definition of B. However, B needs to know about A, but does not need the full definition, so you need the forward declaration of A.