Friend class and Friend function in C++: A friend class can access private and protected members of other classes in which it is declared as a friend. And in sometimes useful to allow a particular class to access private members of other classes. Friendship relation in C++ is always granted not taken. For example, a LinkedList class may be allowed to access private members of the Node.
Syntax:
class A
{
friend class B; //class B is a friend class
……
}
class B
{
……
}
Friend class in C++
Friendship is not mutual. If class A is a friend of B, then B doesn’t become a friend of A automatically.
Friend Class Example
#include<iostream> class A { private: int a; public: A() { a=0; } friend class B;//Friend Class }; class B { private: int b; public: void showA(A& x) { //Since B is friend of A, it can access // private members of A std::cout << "A::a=" << x.a; } }; int main() { A a; B b; b.showA(a); return 0; }
Output:
A::a=0
Friend Function in C++
The friend function can grant access to private and protected members. A friend function can be a method of another class. (or) a global function.
Syntax:
class class_name
{
friend data_type function_name(argument/s); //syntax of friend function.
};
Characteristics of a Friend function
- The function is not in the scope of the class to which it has been declared as a friend.
- It cannot be called using the object as it is not in the scope of that class.
- It can be invoked like a normal function without using the object.
- It cannot access the member names directly and has to use an object name and dot membership operator with the member name.
- It can be declared either in the private or the public part.
Friend Function Example:
#include <iostream> class B; class A { public: void showB(B& ); }; class B { private: int b; public: B() { b = 0; } friend void A::showB(B& x); // Friend function }; void A::showB(B &x) { // Since show() is friend of B, it can // access private members of B std::cout << "B::b = " << x.b; } int main() { A a; B x; a.showB(x); return 0; }
Output:
B::b = 0
Global friend Example
#include <iostream> class A { int a; public: A() {a = 0;} friend void showA(A&); //global friend function }; void showA(A& x) { //Since showA() is a friend, it can access //private members of A std::cout << "A::a=" << x.a; } int main() { A a; showA(a); return 0; }
Output:
A::a = 0