+ 10

How valid is the following statement: It is a good idea to avoid using friend functions and classes.

As you may know friend functions and classes can access private data. But granting access to private information defeats the purpose of information hiding. Should we try hard to avoid their usage? Or is using them not that bad? Confused.

30th Jun 2017, 3:29 PM
jay
jay - avatar
7 Answers
+ 9
Friend functions are considered by some as a loophole in OOP, but as mentioned in C++ FAQ, friend enhances encapsulation. It grants selective access to members, just like protected does, and any pre-determined control is better than granting public access. There are times when a function or a class needs to access private members of another class to complete the build of a blueprint for a real-life system. Instead of making those private members public, it is a better idea to make the designated class/function a friend. For classes, we can argue that most issues of having private members of a class which needs to be accessed by another class can be solved using inheritance (by switching all private members to protected members). However, when multiple inheritance is in play and only one class should be able to access specific members from the base class, this is not feasible. In this case, designating a friend class/function is most suitable.
30th Jun 2017, 5:24 PM
Hatsy Rei
Hatsy Rei - avatar
+ 7
Oh ok, so instead of making getter methods for the things the potential friend needs access to we just do that instead?
30th Jun 2017, 5:27 PM
jay
jay - avatar
+ 7
@Jay It really depends on the system. We can also say that inheritance is not needed as long as we have getters and setters. A part of OOP is about recreating real-life systems in programming, and we have to ensure that the blueprint we create imitates the existing system we have as close as possible.
30th Jun 2017, 5:31 PM
Hatsy Rei
Hatsy Rei - avatar
+ 7
I tried to do a search on the issue, but I'm still not sure how the friend keyword is regarded in general. It's just that I do know there are legit reasons to why it is used (much more than what I just typed).
30th Jun 2017, 5:38 PM
Hatsy Rei
Hatsy Rei - avatar
+ 6
Well your explanation seems logical. Especially when it comes to limiting access to said private member to only a certain other class/function. using getters/setters exposes the private member publicly through its interface defeating the private protection anyway.
30th Jun 2017, 5:41 PM
jay
jay - avatar
+ 4
But in general, they are not considered that bad, is what you are saying. ** Quote was from an old uni book
30th Jun 2017, 5:33 PM
jay
jay - avatar