Home »
C++ programming »
C++ find output programs
C++ Friend Function | Find output programs | Set 2
This section contains the C++ find output programs with their explanations on C++ Friend Function (set 2).
Submitted by Nidhi, on June 18, 2020
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;
}
Output:
50 100
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.
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;
}
Output:
main.cpp: In member function ‘void Sample1::fun1()’:
main.cpp:12:9: error: ‘Sample2’ was not declared in this scope
Sample2 S;
^~~~~~~
main.cpp:13:9: error: ‘S’ was not declared in this scope
S.X = 10;
^
main.cpp: In function ‘int main()’:
main.cpp:43:7: error: ‘class Sample2’ has no member named ‘fun’; did you mean ‘fun2’?
S.fun();
^~~
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.
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;
}
Output:
10
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.