Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful to allow a particular class to access private members of other class. For example a LinkedList class may be allowed to access private members of Node.
Friend Function Like friend class, a friend function can be given special grant to access private and protected members. A friend function can be:
a) A method of another class
b) A global function
Following are some important points about friend functions and classes:
1) Friends should be used only for limited purpose. too many functions or external classes are declared as friends of a class with protected or private data, it lessens the value of encapsulation of separate classes in object-oriented programming.
2) Friendship is not mutual. If class A is a friend of B, then B doesn’t become a friend of A automatically.
3) Friendship is not inherited (See this for more details)
4) The concept of friends is not there in Java.
A simple and complete C++ program to demonstrate friend Class
A simple and complete C++ program to demonstrate friend function of another class
B::b = 0
A simple and complete C++ program to demonstrate global friend
A::a = 0
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Can we access private data members of a class without using a member or a friend function?
- C++ Program to swap two members using Friend Function
- C++ interview questions on virtual function and abstract class
- Difference between Base class and Derived class in C++
- How to convert a class to another class type in C++?
- std::any Class in C++
- std::hash class in C++ STL
- std:: valarray class in C++
- Structure vs class in C++
- std::string class in C++
- Array class in C++
- Difference between namespace and class
- std::is_trivially_copy_assignable class in C++ with Examples
- Virtual base class in C++
- std::bad_array_new_length class in C++ with Examples
- std::bad_weak_ptr class in C++ with Examples
- How can we write main as a class in C++?
- C++ String Class and its Applications | Set 2
- Scanner Class in Java
- C++ string class and its applications
Improved By : ajith211