In C++, you can declare multiple classes or functions as friends of a class. Each friend declaration must be on a separate line within the class definition.
This approach allows you to provide specific access to various classes and functions.
Here’s how to declare multiple friend functions within a class:
#include <iostream>
class MyClass {
friend void functionOne(MyClass &obj);
friend void functionTwo(MyClass &obj);
private:
int value{10};
};
void functionOne(MyClass &obj) {
std::cout << "Value from functionOne: "
<< obj.value << "\n";
}
void functionTwo(MyClass &obj) {
std::cout << "Value from functionTwo: "
<< obj.value << "\n";
}
int main() {
MyClass obj;
functionOne(obj);
functionTwo(obj);
}
Value from functionOne: 10
Value from functionTwo: 10
Here’s how to declare multiple friend classes within a class:
#include <iostream>
class FriendClassOne;
class FriendClassTwo;
class MyClass {
friend class FriendClassOne;
friend class FriendClassTwo;
private:
int value{20};
};
class FriendClassOne {
public:
void showValue(MyClass &obj) {
std::cout << "Value from FriendClassOne: "
<< obj.value << "\n";
}
};
class FriendClassTwo {
public:
void showValue(MyClass &obj) {
std::cout << "Value from FriendClassTwo: "
<< obj.value << "\n";
}
};
int main() {
MyClass obj;
FriendClassOne f1;
FriendClassTwo f2;
f1.showValue(obj);
f2.showValue(obj);
}
Value from FriendClassOne: 20
Value from FriendClassTwo: 20
Befriending multiple classes or functions provides flexibility in controlling access to a class's private and protected members. This technique should be used judiciously to maintain clean and maintainable code.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to the friend
keyword, which allows classes to give other objects and functions enhanced access to its members