-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path06_friend_function.cpp
102 lines (80 loc) · 2.12 KB
/
06_friend_function.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// // Write a C++ program to demonstrate how a common friend function can be used to exchange the private values of two classes. (Use call by reference method).
// // Header files
#include <iostream>
// // use namespace
using namespace std;
// // forward declaration of class B
class B;
// // define class A
class A
{
private:
// // instance member variables
int a;
public:
// // instance member function to set data
void setData(int a)
{
this->a = a;
}
// // instance member function to get data
int getData() const
{
return a;
}
// // friend function to exchange or swap values of private data members of class A and class B
friend void exchange(A &, B &);
};
// // define class B
class B
{
private:
// // instance member variables
int b;
public:
// // instance member function to set data
void setData(int b)
{
this->b = b;
}
// // instance member function to get data
int getData() const
{
return b;
}
// // friend function to exchange or swap values of private data members of class A and class B
friend void exchange(A &, B &);
};
// // friend function to exchange or swap values of private data members of class A and class B
void exchange(A &objA, B &objB)
{
A objTemp;
objTemp.a = objA.a;
objA.a = objB.b;
objB.b = objTemp.a;
}
// // Main Function Start
int main()
{
// // create an instance of class A
A objA;
// // create an instance of class B
B objB;
// // set data
objA.setData(100);
objB.setData(1000);
// // display values before data exchange
cout << "\n>>>>>>>>> Values Before Data Exchange <<<<<<<<<<<\n";
cout << "\nobjA.a => " << objA.getData();
cout << "\nobjB.b => " << objB.getData();
// // exchange values
exchange(objA, objB);
// // display values before after exchange
cout << "\n\n>>>>>>>>> Values After Data Exchange <<<<<<<<<<<\n";
cout << "\nobjA.a => " << objA.getData();
cout << "\nobjB.b => " << objB.getData();
cout << endl; // Add new line
cin.ignore();
return 0;
}
// // Main Function End