Friend Keyword - RJAE5/2143-OOP GitHub Wiki
Friend Keyword
The reserved word friend has a variety of uses, but not all are seen as good. This keyword when preceding a function from within a class will be grant access to both the private and protected sections of only that particular class for that particular function.
Alternatively, a class can make another entire class a friend, which will allow the friend class and all of its members access to the protected and private members of the base class.
Friend Function Example
In this example, ClassA makes a friend of the function friendFunction(ClassA& a), so when the function is used in main() to access the value of valueA, it works properly. However, since ClassB did not make a friend of the function, it would be unable to access any data from ClassB.
class ClassA
{
friend void friendFunction(ClassA& a); // friend function for ClassA
private:
int valueA = 10;
};
class ClassB
{
private:
int valueB = 20;
};
// friendFunction only has access to ClassA's private members
void friendFunction(ClassA& a)
{
std::cout << "ClassA value: " << a.valueA << std::endl;
// std::cout << "ClassB value: " << a.valueB << std::endl; // This would be an error!
}
int main()
{
ClassA a;
friendFunction(a); // Works fine, as it can access ClassA's private members
return 0;
}
Code adapted from ChatGPT
Friend Class Example
In this example, ClassA makes a friend of the class ClassB, so when the function accessClassA from ClassB is used in main() to access the value of valueA, it works properly. However, any other hypothetical class would not be able to access anything from ClassA unless it were made a friend.
class ClassB; // Forward declaration of ClassB
class ClassA
{
friend class ClassB; // Make ClassB a friend of ClassA
private:
int valueA = 42;
public:
void showValueA()
{
std::cout << "ClassA value: " << valueA << std::endl;
}
};
class ClassB
{
public:
void accessClassA(ClassA &a)
{
// ClassB can access private members of ClassA
std::cout << "ClassB accessing ClassA's value: " << a.valueA << std::endl;
}
};
int main()
{
ClassA a;
ClassB b;
// ClassB can access private members of ClassA due to friendship
b.accessClassA(a); // Output: ClassB accessing ClassA's value: 42
return 0;
}
Code adapted from ChatGPT
Important Notes
- Not all believe the
friendkeyword is good, some argue that it breaks encapsulation - The
friendkeyword cannot be used on an outside function or class to allow it access into any other class, the base class must specify which function/class it is allowing to access the private members.