2. friend Function
2
A function outside the class can be made friend of class
It can access private and protected members of the class in
which it is declared as friend
It is declared inside the class as
friend ret_type function_name(parameters);
Examples
1.Time
2. Complex numbers
3. Matrices
3. 3
friend Function
#include <iostream>
using namespace std;
class Shape
{
double width;
public:
friend void print( Shape S1 );
void set( double wid );
};
// Member function definition
void Shape::set( double wid )
{
width = wid;
}
void print( Shape S )
{
cout << "Width of box : " << S.width ;
}
// Main function for the program
int main( )
{
Shape S1;
S1.set(10.0);
// Use friend function to print the wdith.
print( S1);
return 0;
}
4. Example of friend Function
4
#include<iostream>
using namespace std;
class B
{
int val1,val2;
public:
void get()
{
cout<<"Enter two values:";
cin>>val1>>val2;
}
friend float mean(B ob);
};
5. 5
float mean(B ob)
{
return float(ob.val1+ob.val2)/2;
}
int main()
{
B obj;
obj.get();
cout<<"n Mean value is : "<<mean(obj);
return 0;
}
6. 6
#include <iostream>
using namespace std;
class ONE;
class TWO
{
public:
void print(ONE& x);
};
class ONE
{
int a, b;
friend voidTWO::print(ONE& x);
public:
void getdata()
{
cin>>a>>b;
}
};
7. 7
voidTWO::print(ONE& x)
{
cout << "a is " << x.a << endl;
cout << "b is " << x.b << endl;
}
int main()
{
ONE xobj;
TWO yobj;
xobj.getdata();
yobj.print(xobj);
return 0;
}
8. Friend Class
8
Friend Class can access the private and protected
members of the class for which it is friend ,it is done by a
declaring prototype of this external function within the
class, and with the keyword friend.
Friend class is used in C++ to gain access to protected
members exclusively by the friend class
9. 9
Example of Friend Class
#include<iostream>
using namespace std;
class getdata
{
float num1,num2;
public:
void read()
{
cout<<"nnEnter the First Number : ";
cin>>num1;
cout<<"nnEnter the Second Number : ";
cin>>num2;
}
friend class add;
};
10. 10
class add
{
public:
float c;
void add1(getdata G)
{
c=G.num1+G.num2;
cout<<"nnSum="<<c;
}
};
int main()
{
int cont;
getdata G1;
add A;
do {
G1.read();
A.add1(G1);
cout<<"nnDo you want to continue?
(1-YES,0-NO)";
cin>>cont;
}while(cont==1);
return 0;
}