Friend function

Friend function C++

friend_function_c++

Friend function acts as a friend of the class. It can access the private and protected members of the class. The friend function is not a member of the class, but it must be listed in the class definition. The non-member function cannot access the private data of the class. Sometimes, it is necessary for the non-member function to access the data. The friend function is a non-member function and has the ability to access the private data of the class.

To make an outside function friendly to the class, we need to declare the function as a friend of the class as shown below:

class sample  
{  
   // data members;  
 public:  
friend void abc(void);  
};  

Following are the characteristics of a friend function:

  • The friend function is not in the scope of the class in which it has been declared.
  • Since it is not in the scope of the class, so it cannot be called by using the object of the class. Therefore, friend function can be invoked like a normal function.
  • A friend function cannot access the private members directly, it has to use an object name and dot operator with each member name.
  • Friend function uses objects as arguments.

Let's understand this through an example:

#include <iostream>  
using namespace std;  
class Addition  
{  
 int a=5;  
 int b=6;  
 public:  
 friend int add(Addition a1)  
 {  
     return(a1.a+a1.b);  
 }  
};  
int main()  
{  
int result;  
Addition a1;  
 result=add(a1);  
 cout<return 0;  
}  
Output:
11


If you like dEexams.com and would like to contribute, you can also write your article here or mail your article to admin@deexams.com . See your article appearing on the dEexams.com main page and help others to learn.


Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


Python if , elif and else

Python Conditions and If statements

  • 0
Python for beginners

Learning Python Part 1

  • 3
Struct Alignment and Padding

Struct Alignment and Padding in C++ And C

  • 0
Friend function

Friend function C++

  • 0
Pointers

C++ Pointers

  • 0
Structures

C++ Structures

  • 0
Types of Inheritance in C++

Inheritance and access specifiers C++

  • 0
Java date pattern

Java Date Pattern Syntax

  • 0
Java Date and Calendar

Java Date formats

  • 0
JAVA Data Type

Data types in Java

  • 0
Java unreachable code

Unreachable Code Error in Java

  • 0

Post Comment

Comments(0)

WEB TECHNOLOGY

Articles

×

Forgot Password

Please enter your email address below and we will send you information to change your password.