GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

addition and subtraction of 2 numbers of different classes using friend function?

#include <iostream>

using namespace std;

class B;
class A
{
private:
    int num1;
public:
    A()
    {
        num1=0;
    }
    void set()
    {
        cin>>num1;
    }
    friend class B;
};
class B
{
private:
    int num2;
public:
    B()
    {
        num2=0;
    }
    void set()
    {
        cin>>num2;
    }
    int add(A& Obj1)
    {
        return num2+obj1.num2;
    }
    int diff(A& Obj1)
    {
        return obj1.num1-num2;
    }
};
int main()
{
    A obj1;
    B obj2;
    obj1.set();
    obj2.set();
    cout<<obj2.diff(obj1)<<endl;
    cout<<obj2.add(obj1);
    return 0;
}

asked Mar 7, 2017 by vishal408

1 Answer

If you want to use Friend function then you have to declare that friend function in each class, but the definition of that friend function is given outside the class.

At the time of giving definition friend keyword is not used.

Friend function can access all the private and public members wherever it is declared, friend function does not belongs to any single class thus friend function is called similar to a regular function.

#include <iostream>

using namespace std;

class SecondClass;
class FirstClass
{
private:
    int num1;
public:
    FirstClass()
    {
        num1 = 5;
    }

    friend int add( FirstClass o1, SecondClass o2 );
    friend int sub( FirstClass o1, SecondClass o2 );
};

class SecondClass
{
private:
    int num2;
public:
    SecondClass()
    {
        num2 = 8;
    }

    friend int add( FirstClass o1, SecondClass o2 );
    friend int sub( FirstClass o1, SecondClass o2 );

};

int add( FirstClass o1, SecondClass o2 )
{
    return o1.num1 + o2.num2;
}
int sub( FirstClass o1, SecondClass o2 )
{
    return o1.num1 - o2.num2;
}

int main()
{
    FirstClass obj1;
    SecondClass obj2;

    cout<<add(obj1,obj2)<<endl;
    cout<<sub(obj1,obj2);
    return 0;
}

 

answered Mar 16, 2017 by vipulchasta
...