Do friend
functions violate the concept of encapsulation?
In fact, it doesn't. First of, notice it doesn't violate encapsulation more than public
members do. Are public
members a violation of the concept of encapsulation? Obviously not. More so, in many situations friend
increases encapsulation rather then violates it, as it allows you to maintain the private
stuff as private
, instead of having to expose data system-wide using public
members, which makes the entire concept of it being private
hidden from the naked eye. This is the opposite of delivering intent in your code, and should raise a red flag when noticed. friend
allows you to mitigate this issue, as it gives you control over exactly who can access these members that are being kept private
for everyone to know they are. The C++ FAQ raises one example in which you can use friend
to solve a design issue such that you exercise this control over the access to a point where you haven't increased at all the amount of code that has access to the private
parts.
Shouldn't a simple helper class/function along with setter & getter member functions can rescue this design flaw ?
Well, using a helper class could definitely answer some of the same needs that friend
do, but many times are unjustifiably more cumbersome than just using friend
. About function or getter/setter, that just sounds to me like using public members to directly expose private ones, the disadvantages of which are described above.
... or shouldn't it be treated as a poor design practice ?
As an end note, try avoiding subjective questions in here, like whether something should or shouldn't be treated as X. Let's stick to facts! : )