position: fixed; top: auto !important; margin-left: 112px;

Friend Function in C++

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 <iostream>
using namespace std;
class Demo
{
	 int firstNumber,secondNumber;     // private data members
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 "<<c;
 }


int main()
{
Demo a(12,13);        // Call a parameterised Constructor
add(a);               // Calls a add function 

return 0;
}
Compilation Error :
'firstNumber' is a private member of 'Demo'
'secondNumber' is a private member of 'Demo'

Program using friend function (after scenario)

#include <iostream>
using namespace std;
class Demo
{
	 int firstNumber,secondNumber;     // private data members
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 "<<c;
 }


int main()
{
Demo a(12,13);        // Call a parameterised Constructor
add(a);               // Calls a add function 

return 0;
}

Output :-

Addition is 25

Solve the Quiz of Article

1) Is C++ is a "multi-paradigm" programming language?
Yes
No

2) Can C++ Identifiers be used as a keyword?
Yes
No


Previous Next Article







codzify.com


Largest collection of up-to-date tutorials to learn programming languages. We are focused on easy learning. Massive collection of interview questions one may need for preparation.

Social Profile


Linkedin
Twitter
Facebook

Copyright 2018. All rights reserved.