on Leave a Comment

Friend Function in C++

This article contains Friend Function in C++.

Friend Function in C++

We know that private members of class cannot be accessed outside the class. But when there is need to access the private member outside class, then friend comes in use. A friend function is friend of class, but not a member function.

The friend function is declared inside the class using friend keyword. The friend function can be defined anywhere in the program. The friend function definition does not use either friend keyword or scope resolution operator.

Declaration of Friend Function

Declaration of friend function must be written inside the class using friend keyword. A friend function can be friend of more than one class, so its declaration is written to every class.

Syntax:

class class_name
{
          ...
          ...
public:
          ...
          friend return_type function_name(list of arguments);
}; 

Example:

class A
{
        int a;
public:
        friend void setdata(A,int);
};

Definition of Friend Function

A friend function is defined outside the class. It is defined outside the class without using friend keyword and scope resolution operator.

Example:

class A
{
        int a;
public:
        friend void setdata(A,int);
};
void setdata(A.obj, int x)
{
        obj.a=x;
}

Accessing of Friend Function

Friend function is not a member function of  a class, so it can not be accessed by object of that class. A friend function can indirectly access private members of class.

Friend function can be called like a simple function.

Example:

#include<iostream>
using namespace std;
class A
{
    int a;
public:
    friend void setdata(A &,int);
    void putdata()
    {
        cout<<"\na = "<<a;
    }
};
void setdata(A &obj, int x)
{
    obj.a=x;
}
int main()
{
    A o1;
    setdata(o1,10);
    o1.putdata();
    return 0;
}

OUTPUT:

a=10;

0 comments:

Post a Comment