Why does C++ not allow inherited friendship?

前端 未结 10 1548
终归单人心
终归单人心 2020-11-28 04:11

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 sim

相关标签:
10条回答
  • 2020-11-28 04:38

    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.

    0 讨论(0)
  • 2020-11-28 04:42

    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);
            }
    };
    
    0 讨论(0)
  • 2020-11-28 04:42

    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.

    0 讨论(0)
  • 2020-11-28 04:52

    Why is friendship not at least optionally inheritable in C++?

    I think that the answer to your first question is in this question: "Do your father's friends have access to your privates?"

    0 讨论(0)
提交回复
热议问题