Best Industrial Training in C,C++,PHP,Dot Net,Java in Jalandhar

Monday 15 July 2013

Friend Functions

Friend Functions

A C++ friend functions are special functions which can access the private members of a class. They are considered to be a loophole in the Object Oriented Programming concepts, but logical use of them can make them useful in certain cases. For instance: when it is not possible to implement some function, without making private members accessible in them. This situation arises mostly in case of operator overloading.
 In all other regards, the friend function is just like a normal function. A friend function may or may not be a member of another class. To declare a friend function, simply use the friend keyword in front of the prototype of the function you wish to be a friend of the class. It does not matter whether you declare the friend function in the private or public section of the class.
Friend functions have the following properties:
  • 1) Friend of the class can be member of some other class.
  • 2) Friend of one class can be friend of another class or all the classes in one program, such a friend is known as GLOBAL FRIEND.
  • 3) Friend can access the private or protected members of the class in which they are declared to be friend, but they can use the members for a specific object.
  • 4) Friends are non-members hence do not get “this” pointer.
  • 5) Friends, can be friend of more than one class, hence they can be used for message passing between the classes.
  • 6) Friend can be declared anywhere (in public, protected or private section) in the class.
#include<iostream.h>
#include<conio.h>
class  base
{
    int val1,val2;
   public:
    void get()
    {
       cout<<"Enter two values:";
       cin>>val1>>val2;
    }
    friend float mean(base ob);
};
float mean(base ob)
{
   return float(ob.val1+ob.val2)/2;
}
void main()
{
    clrscr();
    base obj;
    obj.get();
    cout<<"\n Mean value is : "<<mean(obj);
    getch();
}          

Output:

Enter two values: 10, 20
Mean Value is: 15

No comments:

Post a Comment