friend function in cpp

Friend Function


In general only member function of a class have access to the private member of the class.However, it is possible to allow a non-member
function access to the private member of a class by declaring it as a friend of a class. To make a function friend of a class we
include its prototype in the class declaration and preceded it with the 'friend' keyword.

characteristic of friend function--
1. It is not in the scope of the class through which it has been declared as a friend.
2. A friend function cannot be called using the object of that class. It can be invoked like a normal function without
  the help of an object.
3. It cannot access member character directly.
4. It can use object name to access member variable.
5. It can be declared either can be public or protected part of a class without affecting its meaning.
6. Usually, it has the object as an argument.



#include<iostream>
using namespace std;
class FrdTest
{
    int x,y;
public:
    friend void display(FrdTest &obj);
    void getdata()
    {
        cout<<"Enter the value of x and y\n";
        cin>>x>>y;
    }
};
void display(FrdTest &obj)
{
    cout<<obj.x<<" "<<obj.y;
}

int main()
{
    FrdTest aobj;
    aobj.getdata();
    display(aobj);
    return 0;
}





output:---

Enter the value of x and y
12 30
12 30
Process returned 0 (0x0)   execution time : 2.874 s





Comments

Popular posts from this blog

C program that contains a string XOR each character in this string with 0 ,127

Queue in Data Structure(DS)

Implementation of stack Using Array