What are the use cases of friend functions and friend classes

Follow by Email
Facebook0
Facebook
Google+
https://codingsec.net/2017/04/use-cases-friend-functions-friend-classes/

A friend function is a non-member function which can access the private and protected members of a class. To declare an external function as a friend of the class, the function prototype preceded with friend keyword should be included in that class. Syntax for creating a friend function is as follows:

 

Following are the properties of a friend function:

  • Friend function is a normal external function which is given special access to the private and protected members of a class.
  • Friend functions cannot be called using the dot operator or -> operator.
  • Friend function cannot be considered as a member function.
  • A function can be declared as friend in any number of classes.
  • As friend functions are non-member functions, we cannot use this pointer with them.
  • The keyword friend is used only in the declaration. Not in the definition.
  • Friend function can access the members of a class using an object of that class.

 

Following program demonstrates using a friend function:

 

In the above program show_details() function was able to access the private data member name as it is a friend of Student class.

 

Friend Class

 

A friend class is a class which can access the private and protected members of another class. If a class B has to be declared as a friend of class A, it is done as follows:

 

Following are properties of a friend class:

  • A class can be friend of any number of classes.
  • When a class A becomes the friend of class B, class A can access all the members of class B. But class B can access only the public members of class A.
  • Friendship is not transitive. That means a friend of friend is not a friend unless specified explicitly.

 

Following program demonstrates a friend class:

 

In the above program class B has been declared as a friend of class A. That is why it is able to access private member x of class A.

 

Take your time to comment on this article.

Follow by Email
Facebook0
Facebook
Google+
https://codingsec.net/2017/04/use-cases-friend-functions-friend-classes/

Add a Comment

Your email address will not be published. Required fields are marked *

Like the article? please consider sharing it. Thank you

Advertisment ad adsense adlogger