Objective: Write a C++ program to show the use of friend function and friend class.
Code:
#include <iostream>
using namespace std;
class B; // forward declaration
class A
{
int x;
public:
void setdata(int i)
{
x = i;
}
// Declare class B as a friend class
friend class B;
// Declare the min function as a friend function
friend void min(A, B);
};
class B
{
int y;
public:
void setdata(int i)
{
y = i;
}
// Member function of B accessing private member x of A
void showAdata(A& a)
{
cout << "Value of x from class A: " << a.x << endl;
}
// Declare the min function as a friend function
friend void min(A, B);
};
void min(A a, B b)
{
if (a.x <= b.y)
cout << a.x << std::endl;
else
cout << b.y << std::endl;
}
int main()
{
A a;
B b;
a.setdata(10);
b.setdata(20);
// Calling friend function
min(a, b);
// Using friend class functionality
b.showAdata(a);
return 0;
}
Output:
No comments:
Post a Comment