Wednesday, January 9, 2013

Friend function

Friend function:
A function with the keyword "friend" which is used to access private member variable of  class without being a member function of the class is known as friend function.
Characteristics:
  1. It is not in the scope of the class to which it has been declared as friend.
  2. Since, it isnot the scope of the class, it can be called using the object of that class.
  3. It can be invoked like a normal function without the help of any object.
  4. Unlike member function, it can't access the member names directly and has to use object name and dot membership operator with each member name.
  5. It can be declared either in the public of private part of class without affecting its meaning.
  6. Usually, it has the objects as arguments.
Example:
class number
{
int a;
int b;
public:
void getdata()
friend int sum(number n);
};
void number::getdata()
{
cout<<"enter the two numbers";
cin>>a>>b;
}
int sum (number n);
{
return(n.a+n.b);
}
void main()
{
number s;
s.getdata();
cout<<sum(s);
}


Function friendly to two class
To swap the contents of private member of two class
class xyz; class abc
{
int a;
public:
void setdata(int m)
{
a=m;
}
friend void swap(abc &obj1, xyz &obj2)
void display()
{
cout<<"a="<<a;
}};
class xyz
{
int b;
public:
void setdata(int m)
{
b=m;
}
friend void swap(abc &obj1, xyz &obj2)
void display()
{
cout<<"b="<<b;
}};
void swap(abc &obj1, xyz &obj2)
{
int temp=obj.a;
obj.a=obj.b;
obj.b=temp;
}
void main()
{
abc a1;
xyz x1;
a1.setdata();
x1.setdata();
x1.display();
a1.display();
swap(a1, x1);
a1.display();
x1.display();
}

1 comment:

  1. Lucky Club - Online casino site - Lucky Club Live
    Lucky Club is a new online casino. Lucky Club is a fully licensed online casino where luckyclub you can play both slot games for free. There is a minimum

    ReplyDelete