C++ Program to Demonstrate the working of the friend function in C++.


January 22, 2023, Learn eTutorial
1054

What is a Friend function in C++?

A friend function of a class is defined as a function that is not defined in that class but it has all the right to access all the public, protected, and private members and data of that class. A friend function will not be taken as a member function of a class even if it is mentioned in the class definition. 

To declare a function as a friend of a class, precede the function prototype in the class definition with the keyword friend as follows −

class className {
    ... .. ...
    friend returnType functionName(arguments);
    ... .. ...
}

How to create a C++ program to demonstrate the working of the friend function

Create a class Distance and declare a private variable meter.  Declare a friend function addFive()

Friend int addFive(Distance)

where,

  • Friend – keyword
  • Int–return type
  • addFive – function name
  • Distance – arguments

Here addFive() can access both private and public data members. The private members from the friend function are accessed by:
    d.meter += 5;
    return d.meter;

Create an object D for the class Distance in the main function and access the friend function using this object
cout << "Distance: " << addFive(D);

Algorithm

Step 1:  Call the header file iostream.

Step 2: Use the namespace std.

Step 3: Create a class Distance

Step 4: Declare a variable meter as private.

Step 5: Declare a friend function addFive().

Step 6: Define a public function Distance().

Step 7: Define the friend function.

Step 8: Open the integer type main function; int main().

Step 9: Create an object to the class Distance.

Step 10: Access the friend function using the object and display the result on the screen.

Step 11: Exit
 

C++ Source Code

                                          // C++ program to demonstrate the working of friend function

#include <iostream>
using namespace std;

class Distance {
    private:
        int meter;
        
        // friend function
        friend int addFive(Distance);

    public:
        Distance() : meter(0) {}
        
};

// friend function definition
int addFive(Distance d) {

    //accessing private members from the friend function
    d.meter += 5;
    return d.meter;
}

int main() {
    Distance D;
    cout << "Distance: " << addFive(D);
    return 0;
}
                                      

OUTPUT

Distance: 5