Friend functions and classes provide a way to extend the accessibility of a class's private and protected members beyond the class itself, which can be useful in certain scenarios.
However, this can also impact the principle of encapsulation, which is a core concept in object-oriented programming.
Encapsulation aims to hide the internal state and implementation details of an object, exposing only what is necessary through a public interface.
By making certain functions or classes friends, you are giving them access to the internals of your class, which can be seen as a breach of this encapsulation principle.
While this might seem like a downside, it has its benefits:
Here's an example to illustrate:
#include <iostream>
class MyClass {
friend void LogCalls(MyClass);
public:
void operator()() { ++Calls; }
private:
int Calls{0};
};
void LogCalls(MyClass Functor) {
std::cout << "That functor has been called "
<< Functor.Calls << " times.\n";
}
int main() {
MyClass Functor;
Functor();
Functor();
Functor();
LogCalls(Functor);
}
That functor has been called 3 times.
In this example, the LogCalls()
function needs access to the private Calls
member of MyClass
. Instead of making Calls
public, we declare LogCalls()
as a friend, preserving encapsulation for other parts of the program.
Use friend functions and classes judiciously to strike a balance between encapsulation and the need for certain functions to access private data.
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