Wednesday 14 February 2018

Friend Function In C++

If a function is defined as a friend function of a class, then that function can access all the private and protected data.
friend keyword is used to declare a friend function.
friend function  is declared inside the body of class either in private or public section.We cannot access private or protected data member of any class, to access private and protected data member of any class we need a friend function.
Declaration of friend function
    class class_name  
        {  
    friend data_type function_name(argument/s);  
      };  
Example 1:
#include<iostream.h>
#include<conio.h>
class Student
{
private:
     friend void show(); //friend function declaration
};
void show()  // friend function definition
{
int age=40;
cout<<"Age:"<<age;
}
void main()
{
Student e1;
show();
getch();
}
Output :
Age is:40
Example 2:
#include <iostream.h> 
#include <conio.h> 
class Addition 
{ 
    private: 
        int a,b; 
    public: 
        friend int add(Addition a1); ////friend function declaration
}; 
int add(Addition a1)   // friend function definition
{ 
    a1.a=50;
    a1.b=60;
    int c= a1.a+a1.b;
    return c; 
} 
int main() 
{ 
   Addition  a1; 
    cout<<"Addition is: "<< add(a1)<<endl; 
    return 0; 
}
Output:
Addition is:  110
Note:
Pass class or object as parameters in friend function
friend int add(Addition a1);
Using object ,assign the variable
    a1.a=50;
    a1.b=60;
Pass the object as argument at the time of function call because you passed object as parameters in friend function.
   Addition  a1; 
     add(a1);

No comments:

Post a Comment

apply function in R

1) apply function: It takes 3 arguments matrix,margin and function.. Example: m<-matrix(c(1,2,3,4),nrow=2,ncol=2) m #1 indicates it is ap...