According to the text I am referring to (The Complete Reference by Herbert Schildt) a derived class doesn't inherit friend functions and friend functions may not have a storage-class specifier. That is, they may not be declared as static or extern. Why?
Asked
Active
Viewed 940 times
5
-
Throw the book away and buy a new one. Herb Schildt’s books are [universally vilified](http://www.cs.technion.ac.il/users/yechiel/CS/BadBooksC+C++.html#SchildtAny) for their technical inaccuracies. – Konrad Rudolph Jul 20 '11 at 11:34
2 Answers
9
a derived class doesn't inherit friend functions? […] why?
Because that would break encapsulation: the derived class couldn’t control its friends any longer so it effectively cannot control who has access to its internals.
they may not be declared as static or extern, why?
Because static
would make no sense (it only makes sense in functions belonging to a class, and friend
s are free functions), and extern
would once again violate encapsulation because the class effectively cannot control any longer which function has access to it: due to being extern
, the friend could effectively come from a different compilation unit, unknown to the class.
See Jan’s answer for a correction.

Konrad Rudolph
- 530,221
- 131
- 937
- 1,214
-
3Sorry, the second part of this answer is totally wrong. `static` makes sense for free functions (makes them local to compilation unit) and every free function declaration that does not contain keyword `static` implicitly contains `extern`. Also class is not associated with compilation unit. The friend can effectively come from *any* compilation unit, whether it's "different" can't be defined. – Jan Hudec Jul 20 '11 at 12:02
7
- Inherit class does not inherit friend functions, because there is no point in doing that:
- The friend function itself knows about the class whose friend it is, but it won't magically learn about a new subclass, so it does not need to be it's friend either.
- It is still possible to use the function on the derived class due to the implicit conversion to parent.
- The friend declaration cannot contain
static
norextern
, because it is not part of the function signature, so it's not needed to specify the function. I believe the declaration of the function itself can (outside of the class) contain either.

Aquarius_Girl
- 21,790
- 65
- 230
- 411

Jan Hudec
- 73,652
- 13
- 125
- 172