WELCOME IN THE SEA OF C

Here you find some good quality programs.
If any one want any type of help in C and C++ then you can mail me.
Google

Wednesday, February 11, 2009

C++ :: Friend Function


Use Of Common Friend Function To Exchange The Private Value Of Two Classes.


#include /iostream.h/

class class2; //forward declaration

class class1
{
int val1;
public:
void indata(int a)
{
val1=a;
}
void display(void)
{
cout<< val1 << "\n";
}
friend void exchange(class1 &,class2 &); //common friend function
};

class class2
{
int val2;
public:
void indata(int a)
{
val2=a;
}
void display(void)
{
cout<< val2 << "\n";
}
friend void exchange(class1 &,class2 &); //common friend function
};

void exchange(class1 & x,class2 & y) //definition of friend
{
int temp=x.val1;
x.val1=y.val2;
y.val2=temp;
}

int main()
{
class1 c1;
class2 c2;

c1.indata(10);
c2.indata(20);

cout<< "value before exchange" << "\n";
c1.display();
c2.display();

exchange(c1,c2); //swapping
cout<< "value after exchange" << "\n";
c1.display();
c2.display();

return 0;
}

C++:: Friend Function

A Function Friendly To Two Classes


#include /iostream.h/

class class2; //forward declaration

class class1
{
int x;
public:
void setvalue(int i)
{
x=i;
}
friend void max(class1,class2); //common friend function
};

class class2
{
int a;
public:
void setvalue(int i)
{
a=i;
}
friend void max(class1,class2); //common friend function
};

void max(class1 m,class2 n) //definition of friend
{
if(m.x>=n.a)
cout<< "m is max:" << m.x;
else
cout<< "n is max:" <<>
}

int main()
{
class1 c1;
class2 c2;

c1.setvalue(10);
c2.setvalue(20);

max(c1,c2); //greater then
return 0;
}