Friend Function

Non-member function of any class that can access private members.

 

Must have a prototype as a friend in the class (es) .

 

Cannot use the keyword this .

Compare the area of Rectangle and Triangle

#include<iostream.h>
class Triangle; 

class Rectangle{
private:
float width,length,area;
public:
Rectangle(float w,float l)
{
width=w;
length=l;
area=w*l;
}
friend int sameSize(Triangle t, Rectangle r);
};
//==========================================
class Triangle{
private:
float base,height,area;
public:
Triangle(float b, float h)
{
base=b;
height=h;
area=b*h/2;
}
friend int sameSize (Triangle t, Rectangle r);
};
//==========================================
// Access the private members of both functions
int sameSize(Triangle t, Rectangle r)
{
if(t.area==r.area)
return 1;
else
return 0;
}
//===========================================
void main()
{
Rectangle r(10,10);
Triangle t(20,6);

if(sameSize(t,r))
cout<<"Same size";
else
cout<<"different size";
}

 

Overload operator

#include<iostream.h>

class Time{
private :
int sec;
int min;
int hour;
public:
Time(){sec=0;min=0;hour=0;}
Time(int s,int m,int h)
{
sec=s;
min=m;
hour=h;
}
void setsec(int s){sec=s;}
void setmin(int m){min=m;}
void sethour(int h){hour=h;}
int getsec(){return sec;}
int getmin(){return min;}
int gethour(){return hour;}

//Overloaded operator function to increment this object's time by one second
friend void operator++(Time &);
};//end class Time
//====================================
void operator++(Time &ob)
{
ob.sec++;
if(ob.sec==60){ob.sec=0; ob.min++;}
if(ob.min==60){ob.min=0 ; ob.hour++;}
if(ob.hour==24){ob.hour=0;}
}
//===========================
void main(){
Time o1(10,10,10) ;

// The seconds for o1 are incremented
++o1;

cout<<"\n o1 after incrementing it is "<< o1.gethour()
<< " : "<< o1.getmin() <<" : "<<o1.getsec();
}