Online Classes

Results can only be achieved if you have the focused direction and crystal clear knowledge. To achieve this, you need a mentor. We will help you out by connecting with an expert mentor in the field.

Learn More

Article

Friend Function in C++

1 min 44 sec read

Do you want to access private members of an object outside the class? Then you should declare a function as a friend. These are functions which can access private or protected members of an object. A friend function is called by the passing object as an argument. Such a function has to be declared as the friend within the class.

Program without writing friend function (Before Scenario)

Example :-

#include 
using namespace std;
class Demo
{
// private data members
	 int firstNumber,secondNumber;     
public:
 Demo(int a ,int b)
 {
   firstNumber  = a;
   secondNumber = b;
 }
   void add(Demo); 
};
 void add (Demo demoInstance)
 {
 int c = demoInstance.firstNumber + 
 demoInstance.secondNumber;
 cout<<"Addition is "<
Compilation Error : 'firstNumber' 
is a private member of 'Demo'
 'secondNumber'
 is a private member of 'Demo' 

Program using friend function (after scenario)

#include 
using namespace std;
class Demo
{
// private data members
	 int firstNumber,secondNumber;     
public:
 Demo(int a ,int b)
 {
   firstNumber  = a;
   secondNumber = b;
 }
 friend  void add(Demo); 
};
 void add (Demo demoInstance)
 {
int c = demoInstance.firstNumber + demoInstance.secondNumber;
 cout<<"Addition is "<

Output :-

Addition is 25

Try to execute what you have learnt

Easy to use online data structure compiler where you can execute the programs in your favourite programming language.
(C, C++, Python)

Open Compiler

HTML, CSS and Javascript Real time Web Editor

Execute your HTML, CSS and javascript code in real time with the web editor
(HTML, CSS, Bootstrap, Javascript)

Open Web Editor