G
G
Grigory Dikiy2015-05-07 10:05:08
C++ / C#
Grigory Dikiy, 2015-05-07 10:05:08

Advantage of friend functions?

Hello , the tutor asked when it is preferable to use friend functions instead of just a class , if they can be described by both a friend function and a method . options : inheritance , does not get a this pointer , swiftness is omitted . I don't provide an answer. I can't google it on the internet, can someone more experienced help me?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
monah_tuk, 2015-05-07
@monah_tuk

When you need to provide some access to the inside, while not exposing it completely outside. The function can be defined by the user. Thus, we can somewhat influence the logic of the class without changing its interfaces and without interfering with the binary code. Where can this be useful? At a glance:
1. Unit testing
2. When defining operators (especially any additions, subtractions)
3. Actually, changing, within certain limits, the behavior of a class without inheritance (but you can get it with a stick when the internal structure changes).
But in general, how does it not google? Googled!
1. www.cprogramming.com/tutorial/friends.html last paragraph:

friend and Encapsulation
Some people believe that the idea of ​​having friend classes violates the principle of encapsulation because it means that one class can get at the internals of another. One way to think about this, however, is that friend is simply part of a class's overall interface that it shows the world. Just like an elevator repairman has access to a different interface than an elevator rider, some classes or functions require expanded access to the internals of another class. Moreover, using friend allows a class to present a more restrictive interface to the outside world by hiding more details than may be needed by anything but the friends of the class.
Finally, friends are particularly common in cases of operator overloading because it is often necessary for an overloaded operator to have access to the internals of the classes that are arguments to the operator.

2. www.cplusplus.com/doc/tutorial/inheritance
Typical use cases of friend functions are operations that are conducted between two different classes accessing private or protected members of both.

3. stackoverflow.com/questions/17434/when-should-you-...
Otherwise, if something can be done without friends, do it without them.

E
egor_nullptr, 2015-05-07
@egor_nullptr

Operator Overloading
Free Tip: Read Stroustrup.

S
Stanislav Makarov, 2015-05-07
@Nipheris

What is the advantage of friend functions over class methods?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question