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

Jarx picture Jarx · Mar 5, 2011 · Viewed 9k times · Source

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?

Answer

CB Bailey picture CB Bailey · Mar 5, 2011

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.