Friend Function and Friend Class in C++

As we know that the "data-members" and "member-function" outside of the class which are "private" or "protected" in nature(Access Specifier) cannot be accessed with the help of an object. So to access them outside of the class we use a keyword "friend". There are two ways in which we can use the keyword "friend", either as "friend Function" or as "friend Class".

LOGO: Friend Function & Friend Class

Friend Function and Friend Class is declared inside the main_class(The class from which you want to access the data-member & member-function) and it is defined outside of that class.


#Friend Class 

When we make a class of  "friend" type and use it to access the private or protected data-members and member-function then it is known as Friend Class.
class A
{
private/protected: //Any one of the access specifier.
int a;
void get( )
{
cout<<a;
}
public: //friend class should be written on the public
friend class B;  //declared inside the class
}; 

class B  //defined outside the class
{
public:
void put(A x) //here 'A' is the class with object 'x'
{
x.a=20;
x.get( );
}
};

int main( )
{
A x; //here 'x' is object of class 'A'
B y; //here 'y' is object of class 'B'
y.put(x); //calling function put( ) with object as an argument
}
           


#Friend Function

When we make a function of  "friend" type and use it to access the private or protected data-members and member-function then it is known as Friend Function.
class A
{
private/protected: //Any one of the access specifier.
int a;
void get( )
{
cout<<a;
}
public: //friend class should be written on the public
friend void put();  //declared inside the class
}; 

void B::put(A x)  //defined outside the class
{
x.a=2;
x.get( );
};

int main( )
{
A x; //here 'x' is object of class 'A'
put(x);
}


 #Difference between friend class & friend function


Friend Class Friend Function
In friend class we use a class to access the private data-member and member function. In friend function we use a function to access the private data-member and member function.
We can also access the inherited members from the help of friend class We can not access the inherited members from the help of friend function





Function Manipulators in C++

Introduction to Object-Oriented Programming language.

For giving some suggestion please comment us or check our "Contact us" page. Also more update related to coding will be added in this Blog later on, so please get attached with this Blog by clicking the follow button. Thank you for your support and time...

Post a Comment

0 Comments