Search code examples
c++c++11visual-c++forward-declarationfriend-function

Member function of a class as friend to another class


In this code , i have made max function of class B friend of class A.I have also done forward declaration of class B.But it is giving error.

#include<iostream>

using namespace std;

class B;

class A
{
   int a;
   public:

   void get()
   {
      cin>>a;
   }

   friend void B :: max(A , B);
};

class B
{
   int b;
   public:

   void get()
   {
      cin>>b;
   }

   void max(A x, B y)
   {
      if (x.a > y.b)
         cout<< " x is greater";
      else cout<<"y is greater";
   }
};

int main()
{
   A x;
   B y,c;
   x.get();
   y.get();
   c.max(x,y);
}

Solution

  • B is incomplete at the point where you declare B::max as a friend method. Thus, compiler does not know if there is such a method.

    This means that you need to

    1. reorder classes, so that A knows B has a method B::max and
    2. Implement the method B::max outside of the class definition, when both classes are complete, because you access internal variables.

    It is also a good idea to pass your arguments by const reference. Use const to emphasise that you are not modifying them. Pass by reference to avoid unnecessary copying.

    So, with this in mind:

    class A;
    
    class B{
        int b;
    public: 
        void get(){
            cin>>b;
        }
        void max(const A& x, const B& y);
    };
    
    class A{
        int a;
    public:
        void get(){
            cin>>a;
        }
        friend void B :: max(const A& , const B&);
    };
    
    void B::max(const A& x, const B& y) {
        if (x.a > y.b)
           cout<< " x is greater";
        else
            cout<<"y is greater";
    }