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.
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.
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;
}
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;
}
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us