There are private and protected members in a class that is inaccessible from outside of the class, constituting one of the concepts of object-oriented programming i.e. data hiding. However, these rules can be broken by a friend function.
A function defined with a friend
keyword is called a friend function. It can access both the private and protected members from outside the class.
Declaration of friend function:
1 2 3 4 5 6 7 | class class_name { ....... friend data_type function_name(arguments); ....... }; |
- A friend can be a member’s function, function template, or function, or a class or class template, in which case the entire class and all of its members are friends.
- Although the friend function appears inside the class, they are not membersfunction.
- They can be declared anywhere in the class.
Example: C++ program for a friend function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include <iostream> using namespace std; class Number { private: int num; public: Number(): num(0) { } friend int add(Number); //friend function }; int add(Number n) { n.num += 20; return n.num; } int main() { Number num; cout<<"Number: "<< add(num)<<endl; return 0; } |
Output:
1 | Number: 20 |
C++ friend class
friend
keyword is also used to declare a friend class in C++. When a class is declared a friend class, all the member functions of the friend class become friend functions.
1 2 3 4 5 6 7 8 9 10 11 | class Two; class One { // class Two is a friend class of class One friend class Two; ... .. ... } class Two{ ... .. ... } |
In the above example, class Two
is a friend class of class One
indicating that we can access all the members of class One from class Two. However, vice-versa is not granted.
Example: C++ program for a friend class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include <iostream> using namespace std; class One { int num = 10; friend class Two; // friend class. }; class Two { public: void print(One &o) { cout<<"Num = "<<o.num; } }; int main() { One o; Two t; t.print(o); return 0; } |
Output:
1 | Num = 10 |