C++: Bad practice to use friend classes instead of writing getters / setters?
Asked Answered
P

2

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?
Pluralism answered 5/3, 2011 at 13:11 Comment(5)
See parashift.com/c++-faq-lite/friends.html#faq-14.2Huan
Read this regarding getters/setters: idinews.com/quasiClass.pdf. In two sentences: 1.) They are an abomination onto OO. 2) If you need them, you need to rethink.Aemia
@Huan that link does not work.Claribelclarice
@JossieCalderon : Updated link: isocpp.org/wiki/faq/friends#friends-and-encap :-]Huan
This older link on stackoverflow is better: #17934Waft
D
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.

Demisemiquaver answered 5/3, 2011 at 13:16 Comment(0)
S
15

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.

Simmonds answered 5/3, 2011 at 13:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.