Sunday 1 February 2015

Friend Function in C++

Structure of the Problem Requirements 

 A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions. In this example there are two classes one is LEP_A and another is LEP_B and a friend function name is combine. Function combine() is the friend function of both classes LEP_A and LEP_B. So, the private data of both class can be accessed from this function.And that friend function can be declare in both Classes.

Source Code

#include <iostream>
using namespace std;
class LEP_B;
class LEP_A
{
    private:
int num;
    public:
LEP_A(): num(9)
{

}
friend int combine(LEP_A , LEP_B);
};
class LEP_B
{
   private:
int num;
   public:
LEP_B(): num(9)
{
}
friend int combine(LEP_A , LEP_B);
};
int combine(LEP_A a1,LEP_B a2)
{
int sum = a1.num+a2.num;
return sum;
}
int main()
{
LEP_A a;
LEP_B b;
cout<<"\n\n\t *********** Friend Function ********** \n\n\n";
cout<<"Number : "<<combine(a,b)<<endl<<endl;
return 0;
}

Output of the Program

Friend Function in C++

Share it Please
asad

About Author!

Asad Niazi is Software Engineer , Programmer, Web Developers and a young mentor of Tech Solutions Desk and Blogging Solutions . Asad Love to writes about Technology, Programming, Blogging and make money online.

0 comments:

Post a Comment