Friend Function in C++

1 min 44 sec read Basic


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

How was the tutorial? Nice. Right?



Deep Concept videos to crack the highly-piad interviews.

Chekout out our Youtube Channel to get detailed video content on important topics in interviews.



What is your Interview Score?

Test your skillset with the curated questions created by experts around the globe.

Book a free test slot. Now !.

It usually takes 30 mins for an online test and this test will be MCQ based. Get detailed analytics based on your test and recommedations with personalised roadmaps.

Book a test slot. Now!

Have questions about the trial coding class?

Chat with our experts to discuss

Connect on WhatsApp


Recommended tutorials

#online compiler for c     #python for programming    

#dfs and bfs algorithm     #programming with c language

#storageclass in C    #listcomprehension in python