In this C++ tutorial, you will learn what is a Friend Function, how to declare a friend function, and how to access private and protected members from a friend function, with examples.

C++ Friend Function

C++ Friend Function can access private and protected members (variables and methods) of the classes in which it is declared as friend.

A global function, or a member function of another class can be declared as a friend function in this class.

Syntax

The syntax to declare a friend function in a class is

friend func_return_type function_name (function_parameters);
ADVERTISEMENT

Examples

1. Global function as Friend function in Class A

In the following program, we define a class: A, in which a function display() is declared as a friend function. So, now display() function can access the private and protected members of class A type objects, in this case its the variable x.

C++ Program

#include <iostream>
using namespace std;

class A;
void display(A& a);

class A {
private:
    int x;
    int y;
public:
    A(int _x) {
        x = _x;
    }
    friend void display(A& a);
};

void display(A& a) {
    cout << "x : " << a.x << endl;
}


int main() {
    A a = A(5);
    display(a);
}

Output

x : 5
Program ended with exit code: 0

2. Member function of Class B as Friend function in Class A

In the following program, we define a class: A, in which a function display() of class B is declared as a friend function. So, now B::display() function can access the private and protected members of class A type objects.

C++ Program

#include <iostream>
using namespace std;

class A;

class B {
public:
    void display(A&);
};

class A {
private:
    int x;
    int y;
public:
    A(int _x) {
        x = _x;
    }
    friend void B::display(A& a);
};

void B::display(A& a) {
    cout << "x : " << a.x << endl;
}

int main() {
    A a = A(5);
    B b = B();
    b.display(a);
}

Output

x : 5
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned what a Friend Function is, how it is used to access the private and protected members of other classes which declared this function as friend, with the help of examples.