FREE E LEARNING PLATFORM
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

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.

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 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

noidatut course







Leave Comment