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

C++ Friend Class

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

Syntax

The syntax to declare a friend class in a class is

</>
Copy
friend class A;

Examples

1. Class A has Friend Class B

In the following program, we define two classes: A and B, where B is declared as a friend class for A. So, now class B type objects can access the private and protected members of class A type objects.

C++ Program

</>
Copy
#include <iostream>
using namespace std;

class A {
private:
    int x;
public:
    A(int _x) {
        x = _x;
    }
    friend class B;
};

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

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

Output

(x, y) : 3, 4
Program ended with exit code: 0

2. Class A has no Friend Class B

Now, with the same above example, let us see what happens if we do not declare that B is a friend class to A.

Since B is not a friend class to A, class A type objects does not allow class B type objects to access its private or protected members.

C++ Program

</>
Copy
#include <iostream>
using namespace std;

class A {
private:
    int x;
public:
    A(int _x) {
        x = _x;
    }
};

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

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

Output

'x' is a private member of 'A'

We get a compiler error saying that variable ‘x’ is a private member in its class definition.

Conclusion

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