What is a Friend Function
In object-oriented programming, a friend function, that is a "friend" of a given class, is a function that is given the same access as methods to private and protected data.
A friend function is declared by the class that is granting access, so friend functions are part of the class interface, like methods. Friend functions allow alternative syntax to use objects, for instance f(x) instead of x.f(), or g(x,y) instead of x.g(y). Friend functions have the same implications on encapsulation as methods.
Program of Friend Function
#include <iostream>
#define MAX_SIZE 100
using namespace std;
class sum{
private:
int num[MAX_SIZE];
int n;
public:
void GetNum(void);
friend int add(void);
};
void sum::GetNum(void){
cout<<"\nEnter the total number (n)\n";
cin>>n;
cout<<"\nEnter the number (n)\n";
for(int i = 0; i<n;i++){
cin>>num[i];
}
}
// Friend
int add(void){
sum obj;
int temp = 0;
obj.GetNum();
for (int i = 0; i < obj.n;i++){
temp +=obj.num[i];
}
return temp;
}
int main(){
int res;
res = add();
cout<<"The sum of n value is= "<<res<<endl;
return 0;
}
Output
Enter the total number (n)
6
Enter the number (n)
8
4
5
2
8
7
The sum of n value is= 34
No comments:
Post a Comment