Saturday, February 25, 2012

C++ Program to Implement Friend Class for Adding two Numbers

Friends are functions or classes declared using the friend keyword.
Friend Class can access the private and protected members of the class for which it is friend to c,it is done by a declaring prototype of this external function within the class, and with the keyword friend.

Friend class is used in C++ to gain access to protected members exclusively by the friend class
The following is an Example Program in C++ using friend class to fins the sum of two numbers
 #include<iostream.h>  
 #include<conio.h>  
 class readint  
 {  
 float a,b;  
 public:  
 void read()  
 {  
 cout<<"\n\nEnter the First Number : ";  
 cin>>a;  
 cout<<"\n\nEnter the Second Number : ";  
 cin>>b;  
 }  
 friend class sum;  
 };  
 class sum  
 {  
 public:  
 float c;  
 void add(readint rd)  
 {  
 c=rd.a+rd.b;  
 cout<<"\n\nSum="<<c;  
 }  
 };  
 void main()  
 {  
 int cont;  
 readint rd;  
 sum s;  
 clrscr();  
 do  
 {  
 clrscr();  
 rd.read();  
 s.add(rd);  
 cout<<"\n\nDo you want to continue?(1-YES,0-NO)";  
 cin>>cont;  
 }while(cont==1);  
 getch();  
 }  

No comments:

Post a Comment

Which is the Best Photo Watermarking Software

Photo Theft is becoming more and more common in the web with the outburst of social websites like Facebook,Google Plus and Image sharing se...