Tutorial Study Image

C++ Friend Function


May 28, 2023, Learn eTutorial
308

The private data of one class will not be accessible to non-member functions of another class. There may be times when we wish two classes to share some functions and data members. In such a situation, we can declare the function as a  friend of these classes, allowing it to access the classes' private and protected data members. What do you mean by a friend function in C++, what is the need for a friend function in C++, and what are the special features of a friend function all these important concepts will be covered in this tutorial with simple examples.

What do you mean by friend function?

Introduction

A friend function is an externally provided function that has access to the protected and private data of the members of the class. That means a function that is not a member of a class but it has accessibility to the class's protected and private members is known as a friend function.

A function template, a member's function, a class or class template, or a function, can all be considered friends. If a class is a friend, then every member of the class is also a friend. Friend functions are typical external functions that have been given special access privileges and they are not class members.

Sometimes it is beneficial to provide certain class access to another class's private members. For example, a LinkedList class might be permitted access to Node's secret members.

For example

The program shows the concept of the friend function


#include<iostream>
using namespace std;

class A {
    int x;
    public:

        A() {
            x = 50;
        }
    friend class B; //friend class
};

class B {
    public: void display(A & t) {
        cout << endl << "value of x=" << t.x;
    }
};

main() {
    A _a;
    B _b;
    _b.display(_a);
    return 0;
}
 

Output:


value of x=50

Class B has been declared as a friend within class A in this case. B is therefore a friend of class A. Private members of class A are accessible to class B.

Friend Function in C++

Friend Function:  A friend function can be given a specific permit to access private and protected members, just like a friend class.

A friend function could be a: 

  1. A member from another class
  2. A global function
  • In C++, there is a special function known as a friend function, although it is not considered a member of a class, it has the ability to access the class's private and protected data.
  • A friend function seems to be a non-member function or ordinary function of a class that is specified as a friend inside the class using the term "friend." All-access rights are granted to a function when it is declared as a friend.
  • The keyword "friend" appears only within the friend function's function declaration, not within the function definition.
  • The dot operator and the object's name are not used when the friend function is called. The object, whose value it wants to access, may be accepted as an argument.
  • Any portion of the class, such as the public, private, or protected, can be used to declare a friend function.

Syntax


class <class_name>    
{    
    friend  <return_type> <function_name>(arg list);  
};
 

Syntax Explanation

  • friend: The keyword "friend" indicates that this function is just a friend function.
  • returnType: The function's return type is returnType.
  • functionName: it is the name of the function that has been added as a class friend.
  • arg list: the arguments given are listed in the arg list.

Example

Program to determine which of the two numbers is larger using the friend function


#include<iostream>
using namespace std;

class Largest {
    int x, y, z;
    public:
        void set_data();
    friend void find_max(Largest);
};

void Largest::set_data() {
    cout << "Please Enter the First Number:";
    cin >> x;
    cout << "Please Enter the Second Number:";
    cin >> y;
}

void find_max(Largest t) {
    if (t.x > t.y)
        t.z = t.x;
    else
        t.z = t.y;

    cout << "Maximum Number is\t" << t.x;
}

main() {
    Largest l;
    l.set_data();
    find_max(l);
    return 0;
}
 

Output:


Please Enter the First Number: 50
Please Enter the Second Number:100
Maximum Number is : 100

Why do we require friend functions?

We require friend functions in unique situations where the private data of a class has to be accessed directly without utilizing objects from that class. Consider the following classes: Director and Doctor. For each of these classes' objects, we might want to use the function gross_ salary. It is not necessary for the function to belong to one of the classes.

They are also utilized in operator overloading since they are more intuitive. The friend function method can be used to overload the frequently used binary arithmetic operator. 

Some special features of friend functions:

  • The scope of a friend function is not the same as the class for which it was designated as a friend. As a result, the functionality is not at all restricted to a single class.
  • The friend function may be a member of another class or even a function that is not inside the scope of the class.
  • Without altering its meaning, a friend function may be declared in either the private or public portion of a class.
  • Since friend functions are outside the scope of the class, they cannot be invoked using class objects.
  • The friend function can be called like any other member function without the need for an object.
  • Friend functions may take class objects as arguments.
  • The member names cannot be directly accessed by a friend function. The object name and dot operator must be used in every member name. For example, Doctor. pay, where pay seems to be the name of the object.

Friend class

A friend class may use the data, members, as well as functions of another class in which it has been declared as a friend. They are employed when we want to grant particular class access to private as well as protected members of a different class.

All member functions of classes that have been declared as friends with another class are converted into friend functions for the friend class. In order to connect the classes, friend functions are needed.

The syntax for friend class


class S; //forward declaration

class P{
  // Other Declarations
  friend class S;
};

class S{
  // Declarations
};
 

Class S is considered a friend of class P in the above example. Class S can therefore access the private data of class P members. This does not imply that members of class P can access private data from members of class S. Before the entity is officially defined, the compiler is informed of its existence through a forward declaration.

To let the compiler know that class S exists, we have declared it using a forward declaration, enabling us to use class S objects in class P.

It is important to note that class friendship is not inherited or mutual unless we make it so. This indicates that class S will be a friend of class P's subclasses because class S is a friend of class P.

Program to demonstrate friend class:


#include <iostream>
using namespace std;

// forward declaration
class ClassY;

class ClassX {
  int digit1;

  // friend class declaration
  friend class ClassY;

  public:
      // constructor to initialize num1 to 10
      ClassX() : digit1(10) {}
};

class ClassY {
    int digit2;

    public:
        // constructor to initialize num2 to 5
        ClassY() : digit2(5) {}

    // member function to multiply num1
    // from ClassX with num2 from ClassY
    int multiply() {
        ClassX m;
        return m.digit1 * digit2;
    }
};

int main() {
    ClassY n;
    cout << "Multiplication: " << n.multiply();
    return 0;
}
 

Output:


Multiplication :50

Two classes, X and Y, have been declared in the above program. ClassX has ClassY as a friend class. As a result, ClassY has access to ClassX's member function. We developed a function called multiply() in ClassY that returns the result of multiplying digits 1 and 2.

We can build objects of ClassX inside of ClassY because ClassY is a friend class. Declaring the ClassY in advance is achievable.