Friend-Function-in-C++ .

In this session i have discussed friend function in C++ .


A friend function is a function that can access the private member of a class . The friend function is not a member of class . It is used in the situation where common function need to more than one class . You make the friend function by using friend keyword with normal function .

Friend function syntax

    class ABC
    {
        private :
            int x,y;
        public :
            friend void show();
    
    };
    

The friend function has cetain special characterstrics as follows .

1-It is not in the scope of class in which it is declared as friend .

2-The friend function can not be called using object with dot operator .

3-The friend function can be invoked like normal function .

4-It can be declared either private or public part of the class without affacting their meaning .

5-Usually , Friend function has object as argument .


Example : Write a program that demonstrate the friend function .

    #include<iostream>
    using namespace std;  
    class A
    {
        int x,y;//by default it is private
        public :
          void getdata(int a,int b)
          {
                x=a;
                y=b;
          }
          friend void sum(A obj);
    };
    friend void sum(A obj)
    {
              int s=obj.x+obj.y;
              cout<<"\nSum :  "<<s;
    }
    int main()
    {
            A obj;
            obj.getdata(20,10);
            obj.sum(obj);
            return 0;
    }
OUTPUT : Sum : 30

Friend function with in two classess .

Example : Write a program that demonstrate the friend function .

    #include<iostream>
    using namespace std;  
    class B; // forward declaration
    class A
    {
        int x;//by default it is private
        public :
          void getdata(int a)
          {
                x=a;
          }
          friend void sum(A obj1,B obj2); //friend function declaration
    };
    class B
    {
        int y;
        public :
          void getdata(int a)
          {
                y=a;
          }
          friend void sum(A obj1,B obj2);//friend function declaration
    };
    void sum(A obj1,B obj2)
    {
              int s=obj1.x+obj2.y;
              cout<<"\nSum :  "<<s;
    }
    int main()
    {
            A obj1;
            obj1.getdata(20);
            B obj2;
            obj2.getdata(10);
            sum(obj1,obj2);//friend function called
            return 0;
    }
OUTPUT : Sum : 30

Welcome to AndroidATPoint.

back image                     next image