This section contains the C++ find output programs with their explanations on C++ Friend Function (set 2).
Program 1:
#include <iostream>
using namespace std;
class Sample1 {
int A, B;
friend class Sample2;
};
class Sample2 {
int X, Y;
public:
Sample2()
{
X = 5;
Y = 5;
}
void fun()
{
Sample1 S;
S.A = 10 * X;
S.B = 20 * Y;
cout << S.A << " " << S.B << endl;
}
};
int main()
{
Sample2 S;
S.fun();
return 0;
}
Program 2:
#include <iostream>
using namespace std;
class Sample1 {
int A, B;
public:
friend class Sample2;
void fun1()
{
Sample2 S;
S.X = 10;
S.Y = 20;
cout << S.X << " " << S.Y << endl;
}
};
class Sample2 {
int X, Y;
public:
friend class Sample1;
Sample2()
{
X = 5;
Y = 5;
}
void fun2()
{
Sample1 S;
S.A = 10 * X;
S.B = 20 * Y;
cout << S.A << " " << S.B << endl;
}
};
int main()
{
Sample2 S;
S.fun();
return 0;
}
Program 3:
#include <iostream>
class SampleB;
class SampleA {
public:
void show(SampleB&);
};
class SampleB {
private:
int VAL;
public:
SampleB() { VAL = 10; }
friend void SampleA::show(SampleB& x);
};
void SampleA::show(SampleB& B)
{
std::cout << B.VAL;
}
int main()
{
SampleA A;
SampleB OB;
A.show(OB);
return 0;
}
Answer Program 1:
Output:
Explanation:
Here, we created two classes Sample1 and Sample2, we made Sample2 class as a friend of Sample1 class. Then Sample2 can access the private members of Sample1.
Here, we access the private members A and B of Sample1 class in the member function fun() of Sample2 class and then we set the value to the members and print values.
Answer Program 2:
Output:
Explanation:
It will generate an error because we are accessing the Sample2 from Sample1 but Sample2 is declared below, so it is not accessible. Then it will generate an error.
Answer Program 3:
Output:
Explanation:
Here, we create two classes SampleA and SampleB. And, we created show() function as a friend of SampleB, then it can access private members of class SampleB.
Then, we defined show() function, where we accessed private member VAL inside function show() of SampleA class and print the value VAL.
need an explanation for this answer? contact us directly to get an explanation for this answer