Friend function

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;  
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;  
 friend int add(Addition a1)  
int main()  
int result;  
Addition a1;  
 cout<return 0;  

If you like and would like to contribute, you can also write your article here or mail your article to . See your article appearing on the 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

C++ Pointers

  • 0

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





Forgot Password

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