C++ class, friendship
Friends are functions or classes declared with the friend keyword. It allows
- A non-member function to access the private and protected members of a class if it is declared a friend of that class.
- a friend class, whose members have access to the private or protected members of another class.
Code Example
Explanation
A class with private members:
- Contains a private variable privateVariable and a private function privateFunc().
- Declares friendFunc as a friend function, allowing it to access the private members.
- Declares FriendClass as a friend class, allowing it to access the private members.
class ClassWithPrivateMembers {
private: // private members
int privateVariable = 20;
void privateFunc() { cout << "this is a private function" << endl; }
// friendship
friend void friendFunc(ClassWithPrivateMembers);
friend class FriendClass;
};
Friend Function friendFunc
- Defined outside the class but has access to the private members of ClassWithPrivateMembers.
- Demonstrates accessing the private function and variable.
void friendFunc(ClassWithPrivateMembers obj) { // friend function
obj.privateFunc(); // access private func
cout << "Accessing private variable from friend function: val = " << obj.privateVariable << endl;
}
Friend Class FriendClass:
- A class that can access the private members of ClassWithPrivateMembers.
- Defines an operator() function to access the private function and variable.
class FriendClass { // friend class
public:
void operator()(ClassWithPrivateMembers obj) {
obj.privateFunc(); // access private func
cout << "Accessing private variable from friend class: val = " << obj.privateVariable << endl;
}
};
Main function
- Creates an object objWithPrivateMembers of ClassWithPrivateMembers.
- Creates an object friendObj of FriendClass.
- Uses friendObj to access private members via the operator() function.
- Calls friendFunc to access private members.
int main() {
ClassWithPrivateMembers objWithPrivateMembers; // obj with private members
FriendClass friendObj; // object of friend class
friendObj(objWithPrivateMembers);
friendFunc(objWithPrivateMembers);
return 0;
}
Conclusion
Class friendship is a powerful feature in C++ that allows for closer integration between classes and functions. It can be useful in scenarios where encapsulation needs to be broken to allow specific classes or functions to access private data, while still maintaining overall data protection.