10

I have two classes which in one aspect work together tightly. They both use functionality of each other that should be only used by them and not by any other class.

  • Is it bad practice if I make those two classes friends so they can directly access and manipulate member variables of each other, without using any getter / setter functions?
Jarx
  • 101
  • 1
  • 1
  • 3
  • 1
    Read this regarding getters/setters: http://www.idinews.com/quasiClass.pdf. In two sentences: 1.) They are an abomination onto OO. 2) If you need them, you need to rethink. – sbi Mar 05 '11 at 14:03
  • See http://www.parashift.com/c++-faq-lite/friends.html#faq-14.2 – ildjarn Mar 05 '11 at 13:17
  • @ildjarn that link does not work. – Jossie Calderon Jun 26 '16 at 18:40
  • @JossieCalderon : Updated link: https://isocpp.org/wiki/faq/friends#friends-and-encap :-] – ildjarn Jun 26 '16 at 19:06
  • This older link on stackoverflow is better: http://stackoverflow.com/questions/17434/when-should-you-use-friend-in-c –  Oct 03 '16 at 06:40

2 Answers2

23

Both getters and setters and friend classes reduce encapsulation and increase coupling. At least friendship restricts the reduced encapsulation to the explicitly specified classes that need the extra access. The fact that the two classes are now tightly coupled need not be a bad thing, they can be considered a single unit of the overall design.

CB Bailey
  • 755,051
  • 104
  • 632
  • 656
14

No, not at all. It's a common thing that effectively, you have one class, but it has to be split up into two for lifetime and other implementation things. In this case, friend classes are definitely the way to go.

If changing the implementation of one class means that you'd have to change the implementation of the other, then this is definitely applicable. Especially if you need interface elements between these two that don't apply to being public.

Friend classes exist for a reason.

Puppy
  • 144,682
  • 38
  • 256
  • 465