Write a c++ program to show Friend function.

#include <iostream>
using namespace std;
class secondclass;
class firstclass{
    public:
      int data1;                                //initialize a variable1 to store value
      void set_data(int number1)   // function to assign number1
    {
        data1=number1;
    }
    friend int addBothData(firstclass x,secondclass y);      //add friend function to first class 
};
class secondclass{
    public:
       int data2;                                            //initialize a variable2  to store value
       void set_data(int number2)                // function to assign number2
        {
            data2=number2;
        }
        friend int addBothData(firstclass x,secondclass y);    //add friend function to second class
};
int addBothData(firstclass x,secondclass y)           //define friend function
{
    return (x.data1+y.data2);
}
int main()
{
    firstclass x;
    secondclass y;
    x.set_data(5);
    y.set_data(6);
    cout<<"addition of two numbers "<<addBothData(x,y);    //call friend function
    return 0;
}


Output:

Comments

Popular posts from this blog

Introduction to Python.

Decision Making Statement.