notes and a sample program on freind function.

c_user's Avatar, Join Date: Aug 2009
Contributor
Hi all.

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

description:-
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.

Last edited by shabbir; 23Aug2009 at 14:16.. Reason: Code blocks
mayjune's Avatar, Join Date: Jun 2009
Invasive contributor
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...