-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemberAndFriendFunction.cpp
More file actions
43 lines (33 loc) · 1.08 KB
/
MemberAndFriendFunction.cpp
File metadata and controls
43 lines (33 loc) · 1.08 KB
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
/*member function and the friend function in one code*/
#include <iostream>
using namespace std;
// Class definition
class MyClass {
private:
int value; // Private member variable to store the value
public:
// Constructor to initialize the value to 0
MyClass() : value(0) {}
// Member function to set the value of the private member
void setValue(int newValue) {
value = newValue;
}
// Member function to get the value of the private member
int getValue() {
return value;
}
// Declaration of the friend function
friend void setPrivateValue(MyClass& obj, int newValue);
};
// Definition of the friend function
void setPrivateValue(MyClass& obj, int newValue) {
obj.value = newValue; // Modifying the private member using the friend function
}
int main() {
MyClass obj;
obj.setValue(42);
cout << "Value using member function: " << obj.getValue() << endl;
setPrivateValue(obj, 99);
cout << "Value using friend function: " << obj.getValue() << endl;
return 0;
}