2

I was reading about friend keyword in c++ and couldn't understand why we need such a thing. For example, I was told that since the following function:

bool operator==(const Rational& r1, const Rational&r2);

needs to access private members like r1.numerator we should give it access by declaring it as Friend, But on the other side I have a function called GetNumerator() so why can't I just change r1.numerator with r1.GetNumerator()?

BDL
  • 21,052
  • 22
  • 49
  • 55
  • read [this](https://stackoverflow.com/questions/17434/when-should-you-use-friend-in-c) – yaodav May 25 '20 at 07:15
  • Think a bit larger. What if you need to use members in that coparison that are not exposed by public getters? That's when you need `friend`. – Lukas-T May 25 '20 at 07:16
  • @churill that's when I write more getters :-) –  May 25 '20 at 07:17
  • 5
    Does this answer your question? [When should you use 'friend' in C++?](https://stackoverflow.com/questions/17434/when-should-you-use-friend-in-c) – nayab May 25 '20 at 07:18
  • So it's either getters or friends? what's the advantage of one on the other? –  May 25 '20 at 07:18
  • @nayab not exactly, I mean why can't we only use getters for this? –  May 25 '20 at 07:20
  • @smith_brown And that's the point where you need to think bigger again ;) You probably didn't write larger programs yet. If you are fine with exposing _every_ member via getters that's good for you, but it's usually not what you want or can do for larger classes. – Lukas-T May 25 '20 at 07:23
  • Personally I rarely find a need for using friends. The `==` operator can be implemented as a member function then you don't need friends or getters – Alan Birtles May 25 '20 at 07:23
  • @smith_brown with getter, every one can access the value, but with friend only friends can access the value. – nayab May 25 '20 at 07:53
  • 2
    In general you would use the getter. One reason why you would use `friend` could be if you have a way to do the comparison meaningful faster with a private member variable for which no getter exits, e.g. if you can do the comparison based on some internal knowledge, but you don't want to expose that, because that information could change in a future version of your code and should stay private for that. – t.niese May 25 '20 at 07:54
  • Writing unit tests for private data is the second large area where I usually use friend. No need to expose implementation details of a class to the user. – BDL May 25 '20 at 08:25
  • If anything other than a member of a class needs to directly access (without the help of a member function of the class) that class's private data, then that "anything" needs to be a `friend`. That is the means by which a class explicitly grants access to its private data to something (another class, a function) outside itself. – Peter May 25 '20 at 09:37

0 Answers0