Write a program in C++ to implement friend function in Class.

Algorithm:
1. Create the class and declare the data member as private.
2. Declare the friend function using the keyword friend.
3. Perform the operation of adding two private variables in the friend function.

4. Display the result.

Implementation of above program in C++
#include <iostream>
using namespace std;
class myclass 
{
int a, b;
public:
friend int sum(myclass x);
void set_ab(int i, int j);
};
void myclass::set_ab(int i, int j)
{
a = i;
b = j;
}
// Note: sum() is not a member function of any class.
int sum(myclass x)
{
/* Because sum() is a friend of myclass, it can directly access a and b. */
return x.a + x.b;
}
int main()
{
myclass n;
n.set_ab(13, 44);
cout << sum(n);
return 0;
}

The above program is tested on www.jdoodle.com

Output:
57


Thanks
Mukesh Rajput
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: