Friend Class and Friend Functions in C++
As we know that a class cannot access the private members of other class. Similarly a class that doesn’t inherit another class cannot access its protected members. That is why we have “Friend Class and Friend Functions in C++”.
Friend Class:
A friend class is a class that can access the private and protected members of a class in which it is declared as a friend. This is needed when we want to allow a particular class to access the private and protected members of a class.
Function Class Example
In this example, we have two classes XYZ
and ABC
. The XYZ
class has two private data members ch
and num
, this class declares ABC
as friend class. This means that ABC
can access the private members of XYZ
, the same has been demonstrated in the example where the function disp()
of ABC
class accesses the private members num
and ch
. In this example we are passing object as an argument to the function.
#include <iostream> using namespace std; class XYZ { private: char ch='A'; int num = 11; public: /* This statement would make class ABC * a friend class of XYZ, this means that * ABC can access the private and protected * members of XYZ class. */ friend class ABC; }; class ABC { public: void disp(XYZ obj){ cout<<obj.ch<<endl; cout<<obj.num<<endl; } }; int main() { ABC obj; XYZ obj2; obj.disp(obj2); return 0; }
Output:
A 11
Friend Function:
Similar to friend class, this function can access the private and protected members of another class. A global function can also be declared as friend as shown in the example below:
Friend Function Example
#include <iostream> using namespace std; class XYZ { private: int num=100; char ch='Z'; public: friend void disp(XYZ obj); }; //Global Function void disp(XYZ obj){ cout<<obj.num<<endl; cout<<obj.ch<<endl; } int main() { XYZ obj; disp(obj); return 0; }
Output:
100 Z
Related Posts:
- Data Types in C++
- Operators in C++
- Recursion in C++ with example
- Functions in C++ with example
- goto statement in C++ with example
- Break statement in C++ with example
- Continue Statement in C++ with example
- do-while loop in C++ with example
- While loop in C++ with example
- For loop in C++ with example
- Switch Case statement in C++ with example
- If else Statement in C++
- Constructors in C++
- Enumeration in C++
- OOPs Concepts in C++
- this pointer in C++
- Pointers in C++
- Strings in C++
- Passing Array to Function in C++
- Multidimensional Arrays in C++
- Arrays in C++
- Difference between Function Overloading and Function overriding in C++
- Function Overriding in C++ with examples
- Function overloading in C++ with examples
- Polymorphism in C++ and its types
- Inheritance in C++ with examples
- Destructors in C++ with examples
- Encapsulation in C++ with example
- Interfaces in C++ with Examples
- Abstraction in C++ with example