100

Why is friendship not at least optionally inheritable in C++? I understand transitivity and reflexivity being forbidden for obvious reasons (I say this only to head off simple FAQ quote answers), but the lack of something along the lines of virtual friend class Foo; puzzles me. Does anyone know the historical background behind this decision? Was friendship really just a limited hack that has since found its way into a few obscure respectable uses?

Edit for clarification: I'm talking about the following scenario, not where children of A are exposed to either B or to both B and its children. I can also imagine optionally granting access to overrides of friend functions, etc.

class A {
  int x;
  friend class B;
};

class B {
  // OK as per friend declaration above.
  void foo(A& a, int n) { a.x = n; }
};

class D : public B { /* can't get in A w/o 'friend class D' declaration. */ };

Accepted answer: as Loki states, the effect can be simulated more or less by making protected proxy functions in friended base classes, so there is no strict need for granting friendship to a class or virtual method heirarchy. I dislike the need for boilerplate proxies (which the friended base effectively becomes), but I suppose that this was deemed preferable over a language mechanism that would more likely be misused most of the time. I think it's probably time I bought and read Stroupstrup's The Design and Evolution of C++, which I've seen enough people here recommend, to get better insight to these types of questions ...

Community
  • 1
  • 1
Jeff
  • 3,475
  • 4
  • 26
  • 35

9 Answers9

100

Because I may write Foo and its friend Bar (thus there is a trust relationship).

But do I trust the people who write classes that are derived from Bar?
Not really. So they should not inherit friendship.

Any change in the internal representation of a class will require a modification to anything that is dependent on that representation. Thus all members of a class and also all friends of the class will require modification.

Therefore if the internal representation of Foo is modified then Bar must also be modified (because friendship tightly binds Bar to Foo). If friendship was inherited then all class derived from Bar would also be tightly bound to Foo and thus require modification if Foo's internal representation is changed. But I have no knowledge of derived types (nor should I. They may even be developed by different companies etc). Thus I would be unable to change Foo as doing so would introduce breaking changes into the code base (as I could not modify all class derived from Bar).

Thus if friendship was inherited you are inadvertently introducing a restriction on the ability to modify a class. This is undesirable as you basically render useless the concept of a public API.

Note: A child of Bar can access Foo by using Bar, just make the method in Bar protected. Then the child of Bar can access a Foo by calling through its parent class.

Is this what you want?

class A
{
    int x;
    friend class B;
};

class B
{
    protected:
       // Now children of B can access foo
       void foo(A& a, int n) { a.x = n; }
};

class D : public B
{
    public:
        foo(A& a, int n)
        {
            B::foo(a, n + 5);
        }
};
Tas
  • 7,023
  • 3
  • 36
  • 51
Martin York
  • 257,169
  • 86
  • 333
  • 562
  • 4
    Bingo. It's all about limiting the damage you can cause by changing a class's internals. – j_random_hacker Aug 25 '10 at 02:12
  • Frankly, the case I'm really thinking about this is the Attorney-Client pattern, where an intermediate acts as a limited interface to outsides classes by presenting wrapper methods to the underlying restricted-access class. Saying that an interface is available to all the children of other classes rather than an exact class would be much more useful than the system at present. – Jeff Aug 25 '10 at 02:42
  • @Jeff: Exposing the internal representation to all children of a class will cause the code to become unchangeable (it also does actually break encapsulation as anybody that wanted to access the internal members only has to inherit from Bar even if they are not really a Bar). – Martin York Aug 25 '10 at 03:07
  • @Martin: Right, in this scheme the friended base could be used to get at the friending class, which could be simple encapsulation violation in many (if not most) cases. However, in situations where the friended base is an abstract class, any derived class would be coerced into implementing a reciprocal interface of its own. I'm not sure whether an 'impostor' class in this scenario would be considered to be breaking encapsulation or to be violating an interface contract if it didn't try to faithfully act its claimed role properly. – Jeff Aug 25 '10 at 03:37
  • @Martin: Right, that is the effect that I want and sometimes actually use already, where A is actually a reciprocally friended interface to some restricted access class Z. The common complaint with the normal Attorney-Client Idiom seems to be that the interface class A has to boilerplate call wrappers to Z, and in order to extend access to subclasses, A's boilerplate has to be essentially duplicated in every base class like B. An interface normally expresses what functionality a module wants to offer, not what functionality in others it wants to use itself. – Jeff Aug 25 '10 at 13:53
10

C++ Standard, section 11.4/8

Friendship is neither inherited nor transitive.

If friendship would be inherited, then a class that wasn't meant to be a friend would suddenly have access to your class internals and that violates encapsulation.

Tas
  • 7,023
  • 3
  • 36
  • 51
David
  • 3,324
  • 2
  • 27
  • 31
  • 2
    Say Q "friends" A, and B is derived from A. If B inherits the friendship from A, then because B is a type of A, technically it IS an A that has access to Q's privates. So this doesn't answer the question with any practical reason. – mdenton8 Jun 25 '15 at 20:02
10

A friended class may expose its friend through accessor functions, and then grant access through those.

class stingy {
    int pennies;
    friend class hot_girl;
};

class hot_girl {
public:
    stingy *bf;

    int &get_cash( stingy &x = *bf ) { return x.pennies; }
};

class moocher {
public: // moocher can access stingy's pennies despite not being a friend
    int &get_cash( hot_girl &x ) { return x.get_cash(); }
};

This allows finer control than optional transitivity. For example, get_cash may be protected or may enforce a protocol of runtime-limited access.

Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
2

Because it's just unnecessary.

The usage of the friend keyword is itself suspicious. In term of coupling it's the worst relationship (way ahead of inheritance and composition).

Any change to the internals of a class have a risk to impact the friends of this class... do you really want an unknown number of friends ? You would not even be able to list them if those who inherit from them could be friends also, and you would run in the risk of breaking your clients code each time, surely this is not desirable.

I freely admit that for homework/pet projects dependency is often a far away consideration. On small size projects it doesn't matter. But as soon as several persons work on the same project and this grows into the dozens of thousands of lines you need to limit the impact of changes.

This bring a very simple rule:

Changing the internals of a class should only affect the class itself

Of course, you'll probably affect its friends, but there are two cases here:

  • friend free function: probably more of a member function anyway (I am think std::ostream& operator<<(...) here, which is not a member purely by accident of the language rules
  • friend class ? you don't need friend classes on real classes.

I would recommend the use of the simple method:

class Example;

class ExampleKey { friend class Example; ExampleKey(); };

class Restricted
{
public:
  void forExampleOnly(int,int,ExampleKey const&);
};

This simple Key pattern allows you to declare a friend (in a way) without actually giving it access to your internals, thus isolating it from changes. Furthermore it allows this friend to lend its key to trustees (like children) if required.

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
0

Friend function in a class assigns the extern property to the function. i.e. extern means that the function has been declared and defined somewhere out of the class.

Hence it means friend function is not a member of a class. So the inheritance only allows you to inherit the properties of a class not external things. And also if inheritance is allowed for friend functions, then a third party class inheriting.

Robert
  • 5,278
  • 43
  • 65
  • 115
0

A guess: If a class declares some other class/function as a friend, it's because that second entity needs privileged access to the first. What use is there in granting the second entity privileged access to an arbitrary number of classes derived from the first?

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • 2
    If a class A wanted to grant friendship to B and its descendants, it could avoid updating its interface for each subclass added or forcing B to write pass-through boilerplate, which is half the point of friendship in the first place I think. – Jeff Aug 24 '10 at 23:05
  • @Jeff: Ah, then I misunderstood your intended meaning. I assumed you meant that `B` would have access to all classes inherited from `A`... – Oliver Charlesworth Aug 24 '10 at 23:08
0

A derived class can inherit only something, which is 'member' of the base. A friend declaration is not a member of the befriending class.

$11.4/1- "...The name of a friend is not in the scope of the class, and the friend is not called with the member access operators (5.2.5) unless it is a member of another class."

$11.4 - "Also, because the base-clause of the friend class is not part of its member declarations, the base-clause of the friend class cannot access the names of the private and protected members from the class granting friendship."

and further

$10.3/7- "[Note: the virtual specifier implies membership, so a virtual function cannot be a nonmember (7.1.2) function. Nor can a virtual function be a static member, since a virtual function call relies on a specific object for determining which function to invoke. A virtual function declared in one class can be declared a friend in another class. ]"

Since the 'friend' is not a member of the base class in the first place, how can it be inherited by the derived class?

Chubsdad
  • 24,777
  • 4
  • 73
  • 129
  • Friendship, although given through declarations like members, aren't really members so much as notifications of which other classes can essentially ignore the visibility classifications on 'real' members. While the spec sections you quote explain how the language operates regarding these nuances and frames behavior in self-consistent terminology, things could have been crafted differently, and nothing above gets to the heart of the rationale, unfortunately. – Jeff Aug 25 '10 at 03:07
0

Friend is good in inheritance like style interface for container But for me, as the first say, C++ lack the propagatable inheritance

class Thing;

//an interface for Thing container's
struct IThing {
   friend Thing;
   protected:
       int IThing_getData() = 0;
};

//container for thing's
struct MyContainer : public IThing {
    protected: //here is reserved access to Thing
         int IThing_getData() override {...}
};

struct Thing {
    void setYourContainer(IThing* aContainerOfThings) {
        //access to unique function in protected area 
        aContainerOfThings->IThing_getData(); //authorized access
    }
};

struct ChildThing : public Thing {
    void doTest() {
        //here the lack of granularity, you cannot access to the container.
        //to use the container, you must implement all 
        //function in the Thing class
        aContainerOfThings->IThing_getData(); //forbidden access
    }
};

For me the problem of C++ is the lack of very good granularity to control all access from anywhere for anything :

friend Thing can become friend Thing.* to grant access to all child of Thing

And more, friend [named area] Thing.* to grant access for a precise are in the Container class via special named area for the friend.

Ok stop the dream. But now, you know an interesting usage of friend.

In another order, you can also found interesting to known all class are friendly with self. In other word, a class instance can call all
members of another instance of same name without restriction:

class Object {
     private:
         void test() {}
     protected:
         void callAnotherTest(Object* anotherObject) {
             //private, but yes you can call test() from 
             //another object instance
             anotherObject)->test(); 
         }
};
0

Simple logic : 'I have a friend Jane. Just because we became friends yesterday does not make all of her friends mine.'

I still need to approve those individual friendships, and the level of trust would be accordingly.