Search code examples
c++memberfriend

Member functions as Friend functions in C++


I am getting an error while running the following code for using friend functions. My class XYZ1 has a friend function which is a member function(findMax) of ABC1 class. My class declarations are as follows

class XYZ1;

class ABC1
{
    int a;
    public :
    ABC1()
    {
        a =20;
    }
    void findMax(XYZ1 p)
    {
        if (p.x > a) cout<< "Max is "<<p.x;
        else cout <<"Max is "<<a;
    }
};

class XYZ1
{
    int x;
    public :
    XYZ1()
    {
        x =10;
    }
    friend void ABC1::findMax(XYZ1);
};

 main()
{
    XYZ1 p;
    ABC1 q;
    q.findMax(p);
}

Error:friend3.cpp:14:7: error: ‘p’ has incomplete type friend3.cpp:4:7: error: forward declaration of ‘struct XYZ1’

Please help


Solution

  • Define your findMax method after class XYZ1 is defined.

    #include <iostream>
    using namespace std;
    
    class XYZ1;
    
    class ABC1
    {
        int a;
        public :
        ABC1()
        {
            a =20;
        }
        void findMax(XYZ1 p);
    };
    
    class XYZ1
    {
        int x;
        public :
        XYZ1()
        {
            x =10;
        }
        friend void ABC1::findMax(XYZ1);
    };
    
    void ABC1::findMax(XYZ1 p)
        {
            if (p.x > a) cout<< "Max is "<<p.x;
            else cout <<"Max is "<<a;
        }
    
    int main()
    {
        XYZ1 p;
        ABC1 q;
        q.findMax(p);
        return 0;
    }