-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathWhy_Friend_Function_I.cpp
58 lines (45 loc) · 1.83 KB
/
Why_Friend_Function_I.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <bits/stdc++.h>
using namespace std;
/*
Friend function example-1 to show why it's required
-When a function needs to access private data members of two or more different/independent classes and do some operation,
and at the same time the function can't be a member function of any one class because it won't be able to access private
members of other class, then friend function comes to rescue in this situation.
Using friend function, a global function can access private members of some class.
*/
#include <iostream>
// Forward declaration of ClassB
class ClassB;
class ClassA {
private:
int privateDataA;
public:
ClassA(int dataA) : privateDataA(dataA) {}
// Declare friend function that needs access to privateDataA and privateDataB
friend void performOperation(const ClassA& objA, const ClassB& objB);
};
class ClassB {
private:
int privateDataB;
public:
ClassB(int dataB) : privateDataB(dataB) {}
// Declare friend function that needs access to privateDataA and privateDataB
friend void performOperation(const ClassA& objA, const ClassB& objB);
};
// Definition of the friend function
void performOperation(const ClassA& objA, const ClassB& objB) {
// Access private members of both ClassA and ClassB
std::cout << "Performing operation with private data from ClassA: " << objA.privateDataA
<< " and ClassB: " << objB.privateDataB << std::endl;
// Perform some operation with private data from both classes
// For simplicity, let's just display the sum of the private data
int result = objA.privateDataA + objB.privateDataB;
std::cout << "Result of the operation: " << result << std::endl;
}
int main() {
ClassA objA(10);
ClassB objB(20);
// Call the friend function to perform the operation
performOperation(objA, objB);
return 0;
}