Test your Programming knowledge

50% users failed to get the best score. It's your turn to test now.
Questions curated by the expert mentors at codzify.com

Start Quiz

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

Recommended Articles

Did you found this article helpful?

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