0

I still don't quite understand the concept of OOP in C++.

Is using friend function a bad practice? Does it reduce encapsulation? Why should I use friend function instead of changing my private members to public members? I found that friend function can reduce a lot of codes(eg. setter/getter methods). When should we use friend functions but not other approach?

Thank you.

la lala
  • 41
  • 2
  • 5
  • `friend` should be used only when really necessary. It breaks the whole idea of making something protected or private, by exposing it to a different part of the code again. And if you overuse it then you have again many unwanted dependencies on protect/private members/functions which dramatically decreases maintainability. There are for sure valid use-cases, but before you use `friend` you need to think about if the need for using `friend` is a design flaw of your code. – t.niese Mar 14 '20 at 17:19
  • `I found that friend function can reduce a lot of codes (eg. setter/getter methods).` less code does not necessarily mean it is better. More importantly, is to ensure that that you know when which part, in what way can change member variables. Using getters and setters to modify the members and making the members private ensures that the class is in full control over keeping its member conistent and valid. If you use friend, then you need to check each friend class how it modifies that class, to be sure that the members stay in a valid state. – t.niese Mar 14 '20 at 17:24

0 Answers0