1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

notes and a sample program on freind function.

Discussion in 'C++' started by c_user, Aug 23, 2009.

  1. c_user

    c_user New Member

    Joined:
    Aug 23, 2009
    Messages:
    86
    Likes Received:
    8
    Trophy Points:
    0
    Occupation:
    Php dev
    Location:
    Bhubaneswar
    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.:)
     
    Last edited by a moderator: Aug 23, 2009
  2. mayjune

    mayjune New Member

    Joined:
    Jun 14, 2009
    Messages:
    817
    Likes Received:
    33
    Trophy Points:
    0
    Occupation:
    Student
    Location:
    Pune,Delhi
    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...
     

Share This Page