Friend Functions and Encapsulation
How do friend functions and classes affect encapsulation?
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:
- Controlled Access: Instead of making a member public and exposing it to the entire program, you can provide access to specific functions or classes that truly need it.
- Enhanced Functionality: Sometimes, external functions or classes need to interact closely with the internal state of another class to provide meaningful functionality, such as logging or analytics.
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.
Friend Classes and Functions
An introduction to the friend
keyword, which allows classes to give other objects and functions enhanced access to its members