Answers for "friend function"

1

use of friend function

We require friend functions whenever we have to 
access the private or protected members of a class. This is 
only the case when we do not want to use the objects of that 
class to access these private or protected members.
Posted by: Guest on August-23-2021
1

friend function

#include<iostream>
using namespace std;
class B; //forward declaration.
class A
{
    int x;
    public:
         void setdata (int i)
           {
              x=i;
           }
    friend void max (A, B); //friend function.
} ;
class B
{
     int y;
     public:
          void setdata (int i)
            {
               y=i;
            }
     friend void max (A, B);
};
void max (A a, B b)
{
   if (a.x >= b.y)
         std:: cout<< a.x << std::endl;
   else
         std::cout<< b.y << std::endl;
}
  int main ()
{
   A a;
   B b;
    a. setdata (10);
    b. setdata (20);
    max (a, b);
    return 0;
}
Posted by: Guest on May-07-2021
0

friend function

#include <iostream>
using namespace std;
class Box
{
   private:
        int length;
   public:
         Box (): length (0) {}
   friend int printLength (Box); //friend function
};
int printLength (Box b)
{
    b. length +=10;
    return b. length;
}
int main ()
{
   Box b;
   cout <<” Length of box:” <<printLength (b)<<endl;
    return 0;
}
Posted by: Guest on May-07-2021

Browse Popular Code Answers by Language