c++ Program to illustrate the use of difference operators using friend function

AIM:
A program to illustrate the use of difference operators to access the class member using friend function

ALGORITHM:

1) Start the process
2) Invoke the classes
3) Call the set_xy() first
a) Assign the value of x and y
b) Print the value of x and y
4) Call the sum() for second(friend)
a) Again assign the temp value of x and y
5) Print the value of x and y
6) Stop the process

PROGRAM

#include<iostream.h>
class M
{
int x;
int y;
public:
void set_xy(int a,int b)
{
x=a;
y=b;
}
friend int sum(M m);
};
int sum(M m)
{
int M ::* px=&M :: x;
int M ::* py=&M :: y;
M *pm=&m;
int s=m.*px + pm->*py;
return s;
}
main()
{
M n;
void (M :: *pf)(int,int)=&M :: set_xy;
(n.*pf)(10,20);
cout<<"Sum="<<sum(n)<<"\n";
M *op=&n;
(op->*pf)(30,40);
cout<<"Sum="<<sum(n)<<"\n";
return(0);
}

Output:

Sum=30
Sum=70

Leave a Reply