Friend Functions | C++ Programming

Friend Functions

Friend Function A function is said to be a friend function of a class if it can access the members (including private members) of the class even if it is not the member function of this class. In other words, a friend function is a non-member function that has access to the private members of the class.

Characteristics of a friend function:

  • A friend function can be either global or a member of some other class.
  • Since the friend function is not a part of the class, it can be declared anywhere in the public, private, and protected sections of the class.
  • It cannot be called by using the object of the class since it is not in the scope of the class.
  • It is called a normal function without the help of any object.
  • Unlike member functions, it cannot access member names directly. So, it has to use an object name and dot operator with each member name (like A.x)
  • It, generally, takes objects as arguments.

The concepts of data hiding and encapsulation dictate that private members of a class cannot be accessed from outside the class, that is, non-member functions of a class cannot access the non-public members (data members and member functions) of a class. However, we can achieve this by using friend functions. To make an outside function friendly to a class, we simply declare the function as a friend of the class as shown below:

Sample Code

#include <iostream>
using namespace std;
class beta;
class alpha
{
    int data;

public:
    void setdata(int d)
    {
        data = d;
    }
    friend int sum(alpha, beta);
};
class beta
{
    int data;

public:
    void setdata(int d)
    {
        data = d;
    }
    friend int sum(alpha, beta);
};
int sum(alpha a, beta b)
{
    return a.data + b.data;
}
int main()
{
    alpha a;
    a.setdata(5);
    beta b;
    b.setdata(10);
    cout << "Sum :" << sum(a, b);
}

Friend Functions in | C++ Programming


Furthermore, a fried function also acts as a bridge between two classes. For example, if we want a function to take objects of two classes as arguments and operate on their private members, we can inherit the two classes from the same base class and put the function in the base class. But if the classes are unrelated, there is nothing like a friend function. For example,

Source Code

#include <iostream>
using namespace std;
class sample
{
    int a;
    int b;

public:
    void setvalue()
    {
        a = 25;
        b = 40;
    }
    friend float mean(sample s);
};
float mean(sample s)
{
    return float(s.a + s.b) / 2;
}
int main()
{
    sample x;
    x.setvalue();
    cout << "Mean value = " << mean(x);

    return 0;
}

Friend Functions in | C++ Programming

Comments

Popular posts from this blog

C Program for SCAN Disk Scheduling Algorithm | C Programming

C program to Find Cartesian Product of Two Sets | C programming

C Program To Check The String Is Valid Identifier Or Not | C Programming