Yes, a friend function can access members of multiple classes if each class declares that function as a friend. This allows the function to have privileged access to the private and protected members of each class.
Consider two classes, ClassA
and ClassB
, both granting friendship to the same function sharedFunction
:
#include <iostream>
// Forward declarations
class ClassA;
class ClassB;
class ClassA {
friend void sharedFunction(ClassA &a, ClassB &b);
private:
int dataA{5};
};
class ClassB {
friend void sharedFunction(ClassA &a, ClassB &b);
private:
int dataB{10};
};
void sharedFunction(ClassA &a, ClassB &b) {
std::cout << "ClassA data: " << a.dataA << "\n";
std::cout << "ClassB data: " << b.dataB << "\n";
}
int main() {
ClassA a;
ClassB b;
sharedFunction(a, b);
}
ClassA data: 5
ClassB data: 10
In this example, sharedFunction
is a friend to both ClassA
and ClassB
. This enables it to access the private data members dataA
and dataB
from instances of these classes.
Here’s an example with operator overloading:
#include <iostream>
// Forward declarations
class ClassX;
class ClassY;
class ClassX {
friend bool operator==(
const ClassX &x, const ClassY &y);
private:
int value{3};
};
class ClassY {
friend bool operator==(
const ClassX &x, const ClassY &y);
private:
int value{3};
};
bool operator==(
const ClassX &x, const ClassY &y) {
return x.value == y.value;
}
int main() {
ClassX x;
ClassY y;
if (x == y) {
std::cout << "Equal\n";
} else {
std::cout << "Not equal\n";
}
}
Equal
In this example, the operator==
function is a friend to both ClassX
and ClassY
, allowing it to access their private value
members and compare them.
Friend functions that access members of multiple classes can be powerful tools for maintaining encapsulation while enabling specific inter-class operations.
This approach should be used thoughtfully to avoid overly complex dependencies between classes.
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