Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   notes and a sample program on freind function. (http://www.go4expert.com/forums/notes-sample-program-freind-function-t19134/)

c_user 23Aug2009 13:25

notes and a sample program on freind function.
 
Hi all.:)

Here i m going to give imp. notes on friend functions..

description:-:crazy:
we knon that private members cannot be accessed from outside the class.This means that a non member function cannot have access to the private data of a class.
If we want to share the data ; in such situation C++ provide the use of friend function by which this problem can be solved.

Below there is a sample program to show the use of friend function....

code:
Code:

#include<iostream.h>
#include<conio.h>
class demo1;
class demo
{
 private:
 int x;
 int sum;
 float avg;
 public:
 void getdata()
 {
  cout<<"enter the valur for x"<<endl;
  cin>>x;
 }
 friend demo cal(demo d,demo1 d1);
 friend void show(demo d);
};
class demo1
{
 int y;
 public:
 void getdata()
 {
  cout<<"enter the value for y"<<endl;
  cin>>y;
 }
 friend demo cal(demo d,demo1 d1);
 //friend void show(demo d);
};
demo cal(demo d,demo1 d1)
{
 d.sum=0;
 d.avg=0;
 d.sum=d.sum+d.x+d1.y;
 d.avg=d.avg+d.sum/2;
 return d;
}
void show(demo d)
{
 cout<<"sum is"<<d.sum<<endl;
 cout<<"average is"<<d.avg;
}
void main()
{
 clrscr();
 demo d;
 demo1 d1;
 d.getdata();
 d1.getdata();
 d=cal(d,d1);
 show(d);
 getch();
}

note:- use of friend function is rarely done becoz it violates the rules of data hiding and encapsulation..

please reply to share more knowledge..... have a good day.:)

mayjune 23Aug2009 15:29

Re: notes and a sample program on freind function.
 
Nice....but try to use ANSI C standard code. Else even if the code is good, it wont qualify for Monthly Article Competitions. Moreover, it is always good to follow ANSI C Standards...


All times are GMT +5.5. The time now is 22:43.