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();  
 }  

6 comments:

Post a Comment

Subscribe

The Source Codes Published in this Blog can be used freely for Educational purposes but should not be reproduced on any other Blog or Website without the consent of the author.