Friend Class and Function in C++


Friend Class

A friend class can access private and protected members of other class in which it is declared as friend.

Here is an example of add a class as a friend class. Class B can access the private member “elem” in Class A.

1
2
3
4
5
class A {
private:
    int elem;
    friend class B;
};


Friend Function

A friend function can be given special grant to access private and protected members. A friend function can be a method of another class, or a global function.

1
2
3
4
5
class A {
private:
    int elem;
    friend int B::search();
};

In this example, only the search() function in class B can access class A’s internal members.

Friendship is not mutual. If class A is a friend of B, B does not become a friend of A automatically. Friendship is not inherited. The concept of friends is not in Java.




Related Posts

Template Specializations in C++

A template specialization is a separate definition in which the...

Copy Constructors in C++

The constructor that takes a single parameter that is a...

Friend Class and Function in C++

A friend class can access private and protected members of...

Templates in C++

A template is a blueprint or formula for creating a...

Polymorphism in C++

Polymorphism means having more than one function with the same...

Interfaces in C++

An interface describes the behavior or capabilities of a C++...