Friend Classes and Functions

Friend Functions and Encapsulation

How do friend functions and classes affect encapsulation?

Abstract art representing computer programming

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.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved