NFC Institute of Engineering & Fertilizer
Research
Object Oriented Programming
Submitted to:
Sir Asim Mubarik
Submitted by:
Hani Jaleel
20-CS-23
Friend Function
Working of friend function:-
Description:-
This following program is a simple example of working of a friend function. A friend function is
that function which can access both private and public members of the program. In the following
program addfive() is a friend function.
Example Code:-
// C++ program to demonstrate the working of friend function
#include <iostream>
using namespace std;
class Distance {
private:
int meter;
// friend function
friend int addFive(Distance);
public:
Distance() : meter(0) {}
};
// friend function definition
int addFive(Distance d) {
//accessing private members from the friend function
d.meter += 5;
return d.meter;
int main() {
Distance D;
cout << "Distance: " << addFive(D);
return 0;
Output:-
Global Function declared as Friend:-
Example Code:-
#include <iostream>
using namespace std;
class XYZ {
private:
int num=100;
char ch='Z';
public:
friend void disp(XYZ obj);
};
//Global Function
void disp(XYZ obj){
cout<<obj.num<<endl;
cout<<obj.ch<<endl;
int main() {
XYZ obj;
disp(obj);
return 0;
Output:-
Global Friend function example:-
Example Code:-
#include <iostream>
using namespace std;
class Temperature
int celsius;
public:
Temperature()
celsius = 0;
friend int temp( Temperature ); // declaring friend function
};
int temp( Temperature t ) // friend function definition
t.celsius = 40;
return t.celsius;
int main()
{
Temperature tm;
cout << "Temperature in celsius : " << temp( tm ) << endl;
return 0;
Output:-
Example #4:-
Description:-
The following example is to making class members as friend. The only difference is that we need
to write class_name :: in the declaration before the name of that function in the class whose
friend it is being declared. The friend function is only specified in the class and its entire body is
declared outside the class.
Example Code:-
#include <iostream>
using namespace std;
class A; // forward declaration of A needed by B
class B
public:
void display(A obj); //no body declared
};
class A
int x;
public:
A()
x = 4;
friend void B::display(A);
};
void B::display(A obj)
cout << obj.x << endl;
int main()
A a;
B b;
b.display(a);
return 0;
}
Output:-