Friend Classes and Functions in C++

//friend1.cpp
#include <iostream>
#include <string>
using namespace std;
class sum{
          int a,b;
          public:
           friend int sum_num(sum x);
           void set_num(int a, int b);
         };
void sum::set_num(int i, int j){
        a = i; b = j;
}

int sum_num(sum x){ // if not friend function, will return a*b
       return x.a + x.b;
}

main(){
       sum n;
       n.set_num(4,5);
       cout << sum_num(n);
       return 0;
}

Output:

9

When a function is declared as friend, it is not a member of any class. But it could access the private and protected parts of the class. freind2.cpp below shows a member function of one class declared as a friend of another class –

#include <iostream>
#include <string>
using namespace std;
#define IDLE 0
#define INUSE 1

class C2; //forward declaration since C2 is passed as argument in C1

class C1{
         int status;
         public:
          void set_status(int state);
          int idle(C2 b);
       };
class C2{
        int status;
         public:
          void set_status(int state);
          friend int C1::idle(C2 b);
       };
void C1::set_status(int state){
       status = state;
}
void C2::set_status(int state){
       status = state;
}
int C1::idle(C2 b){ //only one function is required
     if(status || b.status)
        return 0;
     else
        return 1;
}

main(){
       C1 x;
       C2 y;
   
       x.set_status(IDLE);
       y.set_status(IDLE);
       if(x.idle(y))
           cout << "Both are free\n";
       else
           cout << "One is in use\n";
       y.set_status(INUSE);
       if(x.idle(y))
           cout << "Both are free\n";
       else
           cout << "One is in use\n";
       return 0;
}

Output:

Both are free  
One is in use 

Below are the advantages of using friend functions –

  • in operator overloading
  • easy creation of some i/o functions
  • when two or more class may contain members that are interrelated (as in frend2.cpp shown above)

Derived class do not inherit friend functions. Also friend functions cannot be declared as static or extern.

Friend Classes are used in same special handling situations in which the friend class has access to some of the specified members of another class (class not inherited).

//friend3.cpp
#include <iostream>
#include <string>
using namespace std;
class Month{
        enum value{Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};
        friend class Day;
};
class Day{
      Month::value date;
      public:
        void setd();
        int getd();
     }D1;
void Day::setd(){
      date = Month::Dec;
}
int Day::getd(){
     return(date + 1);
}

main(){
        D1.setd();
        cout << D1.getd();
        return 0;
}

Output:
 12

Add a Comment

Your email address will not be published. Required fields are marked *