Pages

Ads 468x60px

Sunday, 3 June 2012

C++ Program for Friend Functions.


C++ Program for Friend Functions 



            A C++ friend functions are special functions which can access the private members of a class. They are considered to be a loophole in the Object Oriented Programming concepts, but logical use of them can make them useful in certain cases. For instance: when it is not possible to implement some function, without making private members accessible in them. This situation arises mostly in case of operator overloading.



CODE:
#include<iostream.h>
#include<conio.h>
class Operand2; //forward declaration
class Operand1
{
int a;
public :
void get()
{
cout<<"\n\n\t\tEnter the value of Operand1 : ";
cin>>a;
}
friend void add(Operand1,Operand2);
};
class Operand2
{
int b;
public :
void get()
{
cout<<"\n\n\t\tEnter the value of Operand2 : ";
cin>>b;
}
friend void add(Operand1,Operand2);
};
void add(Operand1 op1, Operand2 op2)
{
/* friend fn to add two numbers*/
cout<<"\n\t\t"<<op1.a<<" + "<<op2.b<<" = "<<op1.a+op2.b;
}
void main()
{
Operand1 op1;
Operand2 op2;
clrscr();
cout<<"\n\n\t\tPROGRAM TO ADD TWO NUMBERS USNIG FRIEND FUNCTION\n\n ";
cout<<"\n\t\tINPUT\n\n";
op1.get();
op2.get();
cout<<"\n\n\t\tOUTPUT\n\n";
add(op1,op2);
getch();
}

0 comments:

Post a Comment

Total Pageviews