Ex: 3.
A) Program to implement friend function
Sample 1: Program implementing friend function to display the area of rectangle
#include<iostream>
using namespace std;
class Shape //class definition
{
private:
int iLength, iBreadth;
public:
void getInput()()
{
cout<<"\n Enter the length: ”;
cin>> iLength;
cout<<"\n Enter the breath: ";
cin>> iBreadth;
}
friend void recArea(Shape); // non-member function declared as friend of class ‘Shape’
};
void rectangleArea (Shape s) // non-member function
{
cout<<"Area of Rectangle: “<<s.iLength * s.iBreadth;
}
int main()
{
Shape rec;
rec.getInput();
rectangleArea (rec); //friend function call
return 0;
}
Ex: 3. A) Program to implement friend function
Sample 2: Program implementing friend function to find the sum of private int and float
members of two different classes
#include<iostream>
using namespace std;
class ClassTwo; //class ClassTwo declaration
class ClassOne //class ClassOne definition
{
private:
int iValue;
float fValue;
public:
void getInputs()
{
cout<<" Class: ClassOne";
cout<<"\n--------------------";
cout<<"\nEnter an integer value:";
cin>>iValue;
cout<<"\nEnter a float value:";
cin>>fValue;
}
void displayValues()
{
cout<<"\nClassOne - Private Member Values";
cout<<"\n------------------------------------------";
cout<<"\nThe Integer value is:"<<iValue;
cout<<"\nThe Float value is:"<<fValue;
}
//non-member function myFriend() declared as a friend of ClassOne
friend void myFriend(ClassOne, ClassTwo);
};
class ClassTwo //class ClassTwo definition
{
private:
int iValue;
float fValue;
public:
void getInputs()
{
cout<<"\nClass : ClassTwo";
cout<<"\n---------------------";
cout<<"\nEnter an integer value:";
cin>>iValue;
cout<<"\nEnter a float value:";
cin>>fValue;
}
void displayValues()
{
cout<<"\n\nClassTwo - Private Member Values";
cout<<"\n-------------------------------------------------";
cout<<"\nThe Integer value is:"<<iValue;
cout<<"\nThe Float value is:"<<fValue;
}
//non-member function myFriend() declared also as a friend of ClassTwo
friend void myFriend(ClassOne, ClassTwo);
};
void myFriend(ClassOne obj1, ClassTwo obj2)
{
cout<<"\n\nFriend Function";
cout<<"\n---------------------";
cout<<"\nSum of the Integer private members: "<<obj1.iValue + obj2.iValue;
cout<<"\nSum of the Float private members: "<<obj1.fValue + obj2.fValue;
}
int main()
{
ClassOne obj1;
ClassTwo obj2;
obj1.getInputs();
obj2.getInputs();
obj1.displayValues();
obj2.displayValues();
//friend function is called by passing objects of two classes as arguments
myFriend(obj1, obj2);
return 0;
}