Site icon Bytefreaks.net

C++: Simplified version of ‘Friends with benefits’ demonstrating friend classes

Advertisements

A friend class in C++ can access the private and protected members of the class in which it is declared as a friend.

Friendship may allow a class to be better encapsulated by granting per-class access to parts of its API that would otherwise have to be public.[2] This increased encapsulation comes at the cost of tighter coupling due to interdependency between the classes.

Properties

From Wikipedia: https://en.wikipedia.org/wiki/Friend_class

In the following example we assign both the Man to be a friend of the Woman and the Woman to be a friend of the Man in order to allow both parties to access the private members of the other.

#include <iostream>
using namespace std;

class Man;

class Woman {
  friend class Man;

public:
  void touch(Man man);
private:
  void * body;
};

class Man {
  friend class Woman;

public:
  void touch(Woman woman);
private:
  void * body;
};

void Woman::touch(Man man) {
  void * other = man.body;
}

void Man::touch(Woman woman) {
  void * other = woman.body;
}

int main() {
  Man man;
  Woman woman;

  man.touch(woman);
  woman.touch(man);
  return 0;
}

This post is also available in: Greek

Exit mobile version